JQuery HTML Form and $.serialize()

From CoderLearner
Jump to: navigation, search

What is .serialize() method?

  • serialize() is a jQuery method and it represents a set of form elements.
  • serialize() method create a text string in standard URL-encoded notation.

serialize() syntax

   $('form[name="form_name"]').serialize();

Example 1

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

        <script>
            $(document).ready(function() {
                $('form[name="user_form"]').submit(function(){
                    var data_form = $(this).serialize();
                    $('#content').html(data_form);
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <div id="content"></div>
        <form name="user_form" method="get">
            <table>
                <tr>
                    <td>User Name:</td>
                    <td><input type="text" name="user_name"/></td>
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type="number" name="age"/></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" name="Save" value="Save"/></td>
                </tr>
            </table>
        </form>
    </body>
</html>

Try It

Create a table and insert records

  • This table uses to store user profile information for this tutorial. Use form the $.serialize() methods to get the form's data and send the data by using the Ajax method.

The data from the Ajax will be saved in MySQL's table.

CREATE TABLE user_profile
( 
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(200) NOT NULL,
  age INT NOT NULL,
  PRIMARY KEY(id)
);

INSERT INTO user_profile(name,age)
 VALUES('Bob',39),
       ('Jing',41),
       ('Paul',42),
       ('David',40),
       ('Jamy',20),
       ('Christ',28);

Example: $.get(), $.serialize(), and MySQL

  • The serialize() method uses with ajax $.get() method
  • Form's data will store in MySQL

save_user.php

<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);

$age = $_GET['age'];
$name = $_GET['user_name'];

if (!empty($age) && !empty($name)) {
	if ($db->connect_errno) {
		echo "Failed to connect to MySQL: (" . $db->connect_errno . ") "
                      . $db->connect_error;
	} else {
		$query =
		   "INSERT INTO user_profile (name, age) VALUES(?, ?)";
		$conn = $db->prepare($query);

		if ($conn) {
			$conn->bind_param("si", $name, $age);
			$conn->execute();
			$id = $conn->insert_id;
			echo $id;
		}
		$conn->close();
	}
} else {
	echo 'error';
}
$db->close();
?>

myget_serialize.html

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>User Profile List</title>
        <script type="text/javascript" src="jquery.min.js">
        </script>
        <script>
            $(document).ready(function() {
                $('form[name="user_form"]').submit(function(){
                    var URL = 'save_user.php?';
                    var data_form = $(this).serialize();
                    $.get(URL+data_form,'',function(data){
                        if(data=="error") {
                            $('#content').html('Error processing the form!');
                        }
                        else {
                            $('#content').html('Insert ID: '+ data);
                        }
                    });
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <div id="content"></div>
        <form name="user_form" method="get">
            <table>
                <tr>
                    <td>User Name:</td>
                    <td><input type="text" name="user_name"/></td>
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type="number" name="age"/></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" name="Save" value="Save"/></td>
                </tr>
            </table>
        </form>
    </body>
</html>

Example: $.post(), $.serialize(), and MySQL

  • In the HTML form requires to set the method to "post".
  • Using post method and $.serialize() to send form element.
  • The 'save_user.php' needs to use $_POST to get the form elements.
$(document).ready(function() {
    $('form[name="user_form"]').submit(function(){
	var data_form = $(this).serialize();
	$.ajax({
	       type: 'POST',
	       url:'save_user.php',
	       data:data_form,
	       success:function(response){
		   if(response=="error") {
		     $('#content').html('Error processing the form!');
		   }
		   else {
		     $('#content').html('Insert ID: '+ response);
		   }
	       }
	});		
	return false;
    });
});