Simple form submit with Dojo

I was experimenting with Dojo the other day and to my surprise I did not find a really simple form submit example (using AJAX). What I was looking for was a snippet that took a form id and submitted the form based on that. The endpoint would be the form’s action attribute to make the function reusable on more than one form.

Sitepen has a lot of useful tutorials and they got quite close to what I needed in their Dojo Quick Start Guide. However, their example code seem to be intended to show off Dojo functionality (of course) and used features I did not need.

To the point then. Here is my draft of a form submission using Dojo’s AJAX functionality:

  1. <script type="text/javascript">
  2. /**
  3. * POSTs a form identified by formid using Dojo Ajax
  4. * The server response is shown in the element identified by msgboxid
  5. * TODO: A lot, modify to meet your needs
  6. *
  7. * @param formid The id of the form to submit
  8. * @param msgboxid The id of the element to display the response in
  9. * @return
  10. */
  11. function formSubmit(formid, msgboxid){
  12.  dojo.xhrPost({
  13.   form: formid,
  14.   handleAs: "text",
  15.   handle: function(data,args){
  16.    if(typeof data == "error"){
  17.     console.warn("error!",args);
  18.    }else{
  19.     // show server response in the firebug console
  20.     console.log(data);
  21.    }
  22.    dojo.byId(msgboxid).innerHTML = data;
  23.   }
  24.  });
  25. };
  26. </script>
  27. <div id="fsettingsmsgbox"></div>
  28. <form method="post" action="settings/update" id="fsettings">
  29. <input type="text" name="lastname" />
  30. <input type="button" value="Save settings" onclick="formSubmit('fsettings', 'fsettingsmsgbox');">
  31. </form>

Easy as it should be ;) Yes, there is a lot you could add to this to make it more generic/re-usable/robust but I wanted to keep it as simple as possible so newbies like me can follow.

Posted in Code at September 29th, 2008. Trackback URI: trackback
Tags: ,

One Response to “Simple form submit with Dojo”

  1. December 30th, 2009 at 2:16 pm #Mehdi (from bloody Iran)

    Thank you, you solved my problem. easy and clear.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>