Monday 12 November 2007

AjaxForm class for prototype

Some weeks ago an old mate asked to me the best way to send a form in ajax style and put the result in "div". I think the best way is using prototype javascript framework.
For one project I did a AjaxForm class, it based in an Ajax example of Spring Web Flow.

Here the class:

var AjaxForm = Class.create();
AjaxForm.prototype = {
initialize: function(formElementId) {
this.formElementId = formElementId;
Event.observe(formElementId, 'submit', this.handleSubmitEvent.bindAsEventListener(this), false);
},

handleSubmitEvent: function(event){
var formElement = $(this.formElementId);
if (formElement.tagName.toLowerCase() != 'form') {
throw 'Element ' + formElement + ' is not a FORM element!';
}
var method = formElement.method;
if (method == null) {
method = 'get';
}
var url = formElement.action;
if (url == null) {
throw 'No action defined on ' + formElement;
}
try {
Event.stop(event);
showLoadInfo(formElement);
var params = Form.serialize(formElement, true);

var myRequest = new Ajax.Updater(
{ success: formElement.parentNode },
url,
{
method: method,
parameters: params,
evalScripts: true,
onFailure: errFunc
});
} finally {
return false;
}
}
};


To use this class is very simple, you have to wrapper the form with a div, and create a new AjaxForm, like this example:

<div id="wrapperForm">
<form id="myAjaxForm" action="/dosomething">
...
...
</form>
</div>

<script type="text/javascript">
// <![CDATA[
new AjaxForm('myAjaxForm');
// ]]>
</script>


The result of the post is put in div "wrapperForm". It's fantastic because doesn't break the MVC, remember disable decorators or tiles in the result page, because the result is in the div, not in the page.

I have to update the syntax of AjaxForm class to prototype 1.6, but for example is good enought.

No comments: