Use jQuery’s serialize method to save your coding time

Still now many peoples are  using the query string parameters while creating jquery code for posting their form using ajax method of jquery. We have to spend lot of time in creating the dataString value if the form has lot of elements. But actually we need not prepare this dataString value by typing the names of each and every form elements. Instead of that we can use the serialize method of jquery to collect all the form elements with their name and value and arrange them in the required format.

For example, if a form has two input elements with id’s username and email the query string will be prepared as below,
var username=$(‘#username’).attr(‘value’);
var email=$(‘#email’).attr(‘value’);
var dataString = ‘username=’+ username + ‘&email=’ + email;
$.ajax({
type: “POST”,
url: “ajaxprocess.php”,
data: dataString
});

SERIALIZED STRING FORMAT:
var dataString =$(“#formid”).serialize();

Note that serialize() will codify the special characters. i-e If your email field value is info@qualitypointtech.net, it will convert it into info%40qualitypointtech.net

We need to use the urlDecode method of php to decode these converted characters.

If you are not familiar with jquery, read this

Posted in jQuery Tagged with: ,