Jump to: navigation, search

JQuery HTML Form and $.serialize()

From w3cyberlearnings

Contents

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 TRY-IT

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Profile List</title>
<script 
type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
	$(document).ready(function() {
		$('form[name="user_form"]').submit(function(){
			var data_form = $(this).serialize();
			alert(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>

Create Table and Insert Records

  • This table uses for all the tutorial in this section.
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="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
	$(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;
    });
});


Related Links


Jquery and HTML Elements

  1. jQuery SELECT Element
  2. jQuery Radio Button
  3. jQuery Checkbox Button
  4. jQuery Order and Un-order List
  5. jQuery Form Serialize
  6. jQuery Manipulate HTML Table
  7. jQuery Form Elements Selector
  8. jQuery Validate Form
  9. jQuery and CSS Style Sheet
Navigation
Web
SQL
MISC
References