Saturday, March 10, 2012

Use jQuery’s serialize method to save code writing time.

Recently I came to know that many people are still manually creating the querystring parameters while creating jquery code for posting the form using ajax method of jquery.

For example, if a form has two input elements with ids username and email the querystring will be prepared as below,
var username=$('#username').attr('value');
var email=$('#email').attr('value');

var dataString = 'username='+ username + '&email=' + email;

type: "POST",
url: "ajaxprocess.php",
data: dataString

We should 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.

We can just use the serialize method of jquery to collect all the form elements with their name and value and to arrange them in the required format.

var dataString =$("#formid").serialize();

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

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

If you are not familiar with jquery, you have to first read this jquery forum.

You can subscribe to our Email posts, and you can bookmark this blog for further reading, or you can subscribe to our blog feed.

No comments:

Search This Blog