How and when to use jQuery’s serialize method?

In various articles we have written on jQuery, it has always been evident how this framework contributes to the simplification of code development. In this article we will see how knowledge of all these instruments put at our disposal can further make our life easier and the code more elegant. Today we will analyze the serialize() method; it’s a very interesting instrument which, when applied to a form, extracts field content and prepares a querystring ready to be sent through an ajax request.
If for example we consider a form that requests the first and last name and I enter my data, by applying serialize() to this form (in submit event) I will obtain this string:
first name=Maurizio&last name=Tarchini
Useful, right?
But let’s turn to practice. Take a html document containing a form
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="jquery/jquery-1.4.2.js"></script>
<title>Serialize</title>
</head>
<body>
<form action="#" id="input_form">
first name: <input type="text" name="first name" /><br />
last name: <input type="text" name="last name" /><br />
email: <input type="text" name="email" /><br />
<input type="submit" value="send" name="submit" />
</form>
</body>
</html>
Let’s suppose of wanting to send these data through an asynchronous call (if you are a bit unfamiliar with ajax, in this article you will find everything you need to know).
What we are going to do is extract the field content of the form to the submit event and send them to the elaboration page. The code to achieve that could be this ( I will do this briefly since everything is explained in detail in the article I underlined above):
$(document).ready(function(){
$("#input_form").submit(function(){
var first name = $('input[name=first name]').val();
var last name = $('input[name=last name]').val();
var email = $('input[name=email]').val();
var querystring = "first name="+first name+"&last name="+last name+"&email="+email;
$.ajax({
url: 'elaboration.php',
type: "POST",
data: querystring,
success: function(data) {
//code to execute
}
});
return false;
});
});
As you can see, in submit event, I start extracting one at a time the data contained in the form fields.
Afterwards, I create the querystring variable in the format requested by the ajax method (name=value&name=value…).
Now we are not interested in what the elaboration.php file will do neither are we in which has to carry out the function passed in success parameter. What interests us instead is: What happens if our form has 400 fields? Should we extract the values of 400 fields one by one and construct a very long and complicated querystring to pass to the data parameter? No. By using the serialize() method we can achieve everything with a single and simple line of code.
How to use the serialize method?
Simple. Instead of this
$("#input_form").submit(function(){
var first name = $('input[name=first name]').val();
var last name = $('input[name=last name]').val();
var email = $('input[name=email]').val();
var querystring = "first name="+first name+"&last name="+last name+"&email="+email;
Enough doing this
$("#input_form").submit(function(){
var querystring = $(this).serialize();
The serialize() method will take care of reading all form fields with id input_form (that’s what we mean by this) and creating the string with the pair field name – field content in the correct format and ready to be passed to the data parameter of ajax() method.
You can try with this example that does nothing but prints screen (in submit event) the querystring resulting from field content
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<script type="text/javascript" src="jquery/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#input_form").submit(function(){
var querystring = $(this).serialize();
$('#result').html(querystring);
return false;
});
});
</script>
<title>Serialize</title>
</head>
<body>
<form action="#" id="input_form">
first name: <input type="text" name="first name" id="first name"/><br />
last name: <input type="text" name="last name" id="last name"/><br />
email: <input type="text" name="email" id="email"/><br />
<input type="submit" value="send" name="submit" />
</form>
<p id="result"></p>
</body>
</html>
Attention, the querystring is codified
Just a final remark before conclusion. If you have tried this last script, you must be aware that serialize() codifies (justifiably) the special characters. For example the email will come out like this:
name%40website.com
To decode the string, PHP offers the urldecode() function.
echo urldecode('name%40website.com'); //restores "name@website.com"
While in the previously shown code we could act in this way
$('#result').html(decodeURIComponent(querystring));
Conclusion
In this article we saw an example of how to further simplify code development. If we think of extremely long forms, we witnessed how serialize() resolves the problem of extracting content with a single line of code. By using this method we can enjoy another advantage: The eventual adding or removing of fields from the form should not bring any modification to the jQuery code, with positive effects on maintainability.
*****************************************
L'immagine principale dell'articolo è stata fornita da @Fotolia
9 comments
Trackback e pingback
-
Tweets that mention How and when to use jQuery’s serialize method? | Your Inspiration Web -- Topsy.com
[...] This post was mentioned on Twitter by PHPro, Web RSS News. Web RSS News said: How and when to ... -
Listed on FAQPAL.com
How and when to use jQuery’s serialize method?... In various articles we have written on jQuery, it has always been evident ...



DEMO! ! !! Al the nerds forget to put a demo on them “great” explanation of working thing ?!
Damn….. I don’t read things when there is no demo….
Thank you so much for urldecode() !!!
I’m working on a greek site and i was looking for a solution.
So many tutorials are missing lots of details,
and its hard to find out the reason why something is going wrong, and HOW to fix it!
Great!!!!!!!!
so great!!!!!!!!!
I just wanted to mention, that jQuery’s serialized function is great, but the query string can be sent to the php://input method instead of being stored in the $_POST global array in PHP for example… every language is going to be slightly different. You should expand a little on this and talk about how to turn the serialized string into a usable variable=value array that could be usable.. and then be sure to mention the use of magic_quotes to ensure PHP is actually sanitizing the input before doing anything with it….
Other than that, what a great start on a important and useful subject matter.
If that serialized data to be sent to server then how to get information from that string formed.
Is there is anything to deserialize that string on server side.
Thanks for the valuable information. Thanks once again