Wednesday, December 2, 2009

JQuery - Form content submission via Ajax

If you are using JQuery Ajax to submit data on a form, the regular way to do this is..

$(".submitDetails").bind("click",function()>
{
var dataString="name=Prabhjot&language=Java";
$.ajax({
type: "POST",
url: "someAction.do",
data: dataString,
success: function(data) {
alert("Ajax Submission Done"); }
});

});

As you see, i am trying to submit the form to a struts servlet. The issue is that i want to submit all the elements in the form back to the servlet. For this i would need to build the dataString manually ilke...

var dataString="name=" + $("#personName").val() + "&language=" + $("#languageName").val();
But this is very cumbersome when we have lots of form elements which need to be sent back.
jQuery provides us with the serialize() function to sort this out. This function will automatically create the dataString based on the form elements. So now all we need to do is:

var dataString=$("form").serialize();

and set dataString as the data in the ajax post. The actionForm in struts will be now be populated with these values.

1 comment: