Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Forming Valid Query Strings in jQuery

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 248
    Comment on it

    The jQuery serialize()

    method turns the form values into a valid querystring, as such you can simply append to the string:

    firstName=Maurizio&lastName=Tarchini

    Useful, right?

    Lets take an example:

    <p><em></em></p><form action="#" id="input_form"><em>
           first name: <input name="firstName" type="text"><br>
           last name: <input name="lastName" type="text"><br>
           email: <input name="email" type="text"><br>
           <input value="send" name="submit" type="submit"> <br>
    </em></form><p></p>
    


    Lets say you want to send the form's data like first name, last name etc. using ajax to some other page, Then what you will write in

    <p>*$("#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+"&amp;last name="+last name+"&amp;email="+email;</p>
    
    <pre>    $.ajax({
            url: 'elaboration.php',
            type: "POST",
            data: querystring,
            success: function(data) {
                //code to execute
                    }
            });
            return false;
    </pre>
    
    <p>});*</p>
    

    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).

    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 ?

    <p>$("#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+"&amp;last name="+last name+"&amp;email="+email;</p>
    
    <p>Enough doing this?</p>
    
    <p>$("#input_form").submit(function(){
        var querystring = $(this).serialize();
    }</p>
    

    Will Give you the query String.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: