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.

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags:

The Author

Maurizio is married to the triad PHP - MySql - Apache and, not enough, he has a lover called jQuery. He has a blog where he tries to describe in detail all of "his lovers". His real specialty is the realization of large business application, altough he never refuses the commitment of a website.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

13 comments

  1. johnklavers
  2. Diana
  3. Parveen
  4. Shubham
  5. Vincent

Trackback e pingback

  1. 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 …
  2. 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 …

Leave a Reply

Current day month ye@r *