I am sure you often do a form submission via Ajax and more easily using JQuery. But did you know using a simple method called serialize in JQuery form submission could be more easier. Serialize method converts the form elements & values in an encoded string and submits to the form action. This helps reducing overhead of grabbing values of the form fields and then submitting it, since serialize method grabs the value of the elements placed in the form automatically.
In this tutorial we are going to discuss this step by step, first of all let’s built a HTML form –
<form action="submit.php" method="get" accept-charset="utf-8" class="myform"> <label for="a"></label><input type="text" name="a" value="name" id="a"> <label for="b"></label><input type="text" name="b" value="email" id="b"> <label for="c"></label><input type="text" name="c" value="city" id="c"> <label for="d"></label><input type="text" name="d" value="state" id="d"> <p><input type="submit" value="Continue →"></p> </form>
The above is a usual HTML form and now let us see how do we submit it using JQuery and the serialize method.
In the above code snippet we are serializing the form(having class “myform”) elements and submitting it using JQuery Ajax via post method. We can even serialize some input elements within the form but it’s always better to serialize all form elements and filter them at the server end as required. Above serialize method will send the following serialized string to the server.
This method of submitting form definitely saves lot of time when you are developing your web application. This also takes care of encoding the form values making it a better method than the conventional form submitting using Ajax.But you should note that this method only serializes form elements which are currently active. For eg. the radio button or checkboxes if not selected will not be serialized. Also notice that the submit form button is also not serialized.