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:
-
<script type="text/javascript">
-
/**
-
* POSTs a form identified by formid using Dojo Ajax
-
* The server response is shown in the element identified by msgboxid
-
* TODO: A lot, modify to meet your needs
-
*
-
* @param formid The id of the form to submit
-
* @param msgboxid The id of the element to display the response in
-
* @return
-
*/
-
function formSubmit(formid, msgboxid){
-
dojo.xhrPost({
-
form: formid,
-
handleAs: "text",
-
handle: function(data,args){
-
if(typeof data == "error"){
-
console.warn("error!",args);
-
}else{
-
// show server response in the firebug console
-
console.log(data);
-
}
-
dojo.byId(msgboxid).innerHTML = data;
-
}
-
});
-
};
-
</script>
-
<div id="fsettingsmsgbox"></div>
-
<form method="post" action="settings/update" id="fsettings">
-
<input type="text" name="lastname" />
-
<input type="button" value="Save settings" onclick="formSubmit('fsettings', 'fsettingsmsgbox');">
-
</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.