JQuery Forms Serialize

From CoderLearner
Jump to: navigation, search

Description

$.serialize() method encodes a form data as a string for submission.

 $(form element).serialize();

Example 1

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Serialize</title>
        <script 
            type="text/javascript" 
            src="/lib/jquery-1.7.2.min.js">				 
        </script>
        <script>
            $().ready(function() {
                $('form').submit(function(){
                    var data = $(this).serialize();
                    alert(data);
                    return false;
                });
            });
        </script>
    </head>
    <body> 
        <form>
            <input type="text" name="first"/>
            <input type="text" name="lirst"/>
            <input type="submit" value="Submit"/>
        </form>
    </body>
</html>

Try It

Example 2

Add some additional parameter to the URL

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Serialize</title>
        <script 
            type="text/javascript" 
            src="/lib/jquery-1.7.2.min.js">				 
        </script>
        <script>
            $().ready(function() {
                $('form').submit(function(){
                    var data = $(this).serialize()+'&func=save';
                    alert(data);
                    
                    return false;
                });
            });
        </script>
    </head>
    <body> 
        <form>
            <input type="text" name="first"/>
            <input type="text" name="lirst"/>
            <input type="submit" value="Submit"/>
        </form>
    </body>
</html>

Try It

Example 3

Work with Ajax.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Serialize</title>
        <script 
            type="text/javascript" 
            src="/lib/jquery-1.7.2.min.js">				 
        </script>

        <script>
            $().ready(function() {
                $('form').submit(function(){
                    var dataf= $('form').serialize()+'&func=save';
                    $.ajax({
                        url: 'greeting.php',
                        type:'GET',
                        data:dataf,
                        success:function(data){
                            if(data){
                                $('#content').html(data);
                            }
                        }
                    });
                    return false;
                });
            });
        </script>
    </head>
    <body> 
        <form>
            <input type="text" name="first"/>
            <input type="text" name="lirst"/>
            <input type="submit" value="Submit"/>
        </form>
        <div id="content"></div>
    </body>
</html>

Try It