JQuery serialize() function with $.ajax() post for bigger HTML forms
JQuery provides a very useful function jQuery.serialize() which encodes a set of form elements as a string for submission, and is very useful while we are dealing with huge HTML forms. Basically it will combine your values of form element and then you can post it on any server side scripting page.
For example, suppose you have a very long form with many fields and you want to post it with the help of $.ajax() function, you need to add just few lines of code for jquery from with ajax, no need to add id attribute to any form elements, just have to give id to form itself as follows:
The above JQuery code is bind to the submit event of form, event.preventDefault(); will override the default behavior of form submit mechanism and will avoid page reload after form submit, then we have $.ajax() function, in which have $(this).serialize(); function, here ‘this’ refers to the form which is to be submitted. This function will serialize all the form field and then $.ajax() will submit all the form values to any PHP page or ASP.NET page or JSP.
Consider the following example:
Suppose you have a form with ID frm_details and its having a various fields on it.Then we will have following HTML, JQuery code to achieve the task:
And your somefile.php will have :
and in response jquery will alert the array which is printed on php page.
Quiet Easy Right!!!
CLICK HERE TO VIEW DEMO