What does jQuery.serialize() method do in jQuery?



The serialize() method serializes a set of input elements into a string of data. Let’s say we have the following PHP content in serialize.php file −

<?php if( $_REQUEST["name"] ) {    $name = $_REQUEST['name'];    echo "Welcome ". $name;    $age = $_REQUEST['age'];    echo "<br />Your age : ". $age;    $sex = $_REQUEST['sex'];    echo "<br />Your gender : ". $sex; } ?>

Example

The following is the code snippet showing the usage of this method −

   <head>       <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>               <script>          $(document).ready(function() {                         $("#driver").click(function(event){                                $.post(                   "/jquery/serialize.php",                   $("#testform").serialize(),                                           function(data) {                      $('#stage1').html(data);                   }                    );                                    var str = $("#testform").serialize();                $("#stage2").text(str);             });                          });       </script>    </head>        <body>           <p>Click on the button to load result.html file:</p>               <div id = "stage1" style = "background-color:blue;">          STAGE - 1       </div>       <br />               <div id = "stage2" style = "background-color:blue;">          STAGE - 2       </div>               <form id = "testform">          <table>                         <tr>                <td><p>Name:</p></td>                <td><input type = "text" name = "name" size = "40" /></td>             </tr>                             <tr>                <td><p>Age:</p></td>                <td><input type = "text" name = "age" size = "40" /></td>             </tr>                             <tr>                                <td><p>Sex:</p></td>                                    <td> <select name = "sex">                   <option value = "Male" selected>Male</option>                   <option value = "Female" selected>Female</option>                </select></td>                                 </tr>                             <tr>                <td colspan = "2">                   <input type = "button" id = "driver" value = "Load Data" />                </td>             </tr>                          </table>                   </form>    </body>
Updated on: 2020-02-17T07:07:40+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements