With is this article you can learn the following things within 15 minutes :
Description :
First,In this article we create a responsive form with bootstrap then we validate the form fields with jQuery ValidateEngine plug-in and we post the form values to the server using $.post() method I mean Ajaxs call. Now, we get the all form values in server. We will insert the form data into a database. If you see here, we are using database connection with PDO. We inserted form values into a database by using PDO and get last_insert_id for confirmation of successfull insertion of data into database. Finally, we just fetched the last inserted data and send to client browser in very popular JSON format to display results you can skip this step because we just want to show how we can able to send response to client request in JSON format.
Step1 :
Add below code in HTML head
[css]
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/datepicker.css">
<link rel="stylesheet" href="css/validationEngine.jquery.css">
<link href='http://fonts.googleapis.com/css?family=PT+Serif+Caption|Source+Serif+Pro' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/Save-data-using-Ajax-and-PDO-with-Bootstrap.css">
[/css]
Step2 :
We create a responsive registration form with bootstrap Add below code in HTML body
[html]
<div class="container">
<div class="row">
<div class="registration_form">
<div class="page-header">
<h1>Save data using Ajax and PDO with Bootstrap and ValidationEngine</h1>
</div>
<form class="form-horizontal" role="form" method="post" action="#" id="register-form">
<div class="form-group">
<label for="firstName" class="col-sm-2 control-label">First Name:</label>
<div class="col-sm-6">
<input type="text" name="firstName" class="form-control" id="firstName" placeholder="First Name" data-validation-engine="validate[required]" data-errormessage-value-missing="First Name is required!" >
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">Last Name:</label>
<div class="col-sm-6">
<input type="text" name="lastName" class="form-control" id="lastName" placeholder="Last Name" data-validation-engine="validate[required]" data-errormessage-value-missing="Last Name is required!" >
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Gender:</label>
<div class="col-sm-6">
<label class="radio-inline">
<input type="radio" name="gender" id="gender1" value="male" data-validation-engine="validate[required]"
data-errormessage-value-missing="Please Select Male or Female">Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="gender2" value="female" data-validation-engine="validate[required]" data-errormessage-value-missing="Please Select Male or Female">Female
</label>
</div>
</div>
<div class="form-group">
<label for="dob" class="col-sm-2 control-label">DOB:</label>
<div class="col-sm-6">
<input type="text" name="dob" class="form-control datepicker" id="dob" placeholder=" Date of Birth" data-validation-engine="validate[required]" data-errormessage-value-missing="Please Select your Date of Birth">
</div>
</div>
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">User Name:</label>
<div class="col-sm-6">
<input type="email" name="userName" class="form-control" id="userName" placeholder="Email" data-validation-engine="validate[required,custom[email]]" data-errormessage-value-missing="Your Email is required!" >
</div>
</div>
<div class="form-group">
<label for="passwd" class="col-sm-2 control-label">Password:</label>
<div class="col-sm-6">
<input type="password" name="passwd" class="form-control" id="passwd" placeholder="Password" data-validation-engine="validate[required] text-input" data-errormessage-value-missing="Password is required!">
</div>
</div>
<div class="form-group">
<label for="confirm_passwd" class="col-sm-2 control-label">Confirm-Password:</label>
<div class="col-sm-6">
<input type="password" name="confirm_passwd" class="form-control" id="confirm_passwd" placeholder="Confirm Password" data-validation-engine="validate[required,equals[passwd]] text-input" data-errormessage-value-missing="Confirm Password is required!">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="register" name="submit">Submit</button>
</div>
</div>
</form>
</div><!-- end for class "registration_form" -->
<div class="alert alert-success alert-dismissible success_msg" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<strong>Well done!</strong>Your details submitted Succesfully .
</div>
<div class="table-responsive result" style="display:none">
<div class="page-header">
<h2>Your details :</h2>
</div>
<table class="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Date of Birth</th>
<th>User Name(Email)</th>
<th>Password</th>
</tr>
<tr>
<td id="First_name"></td>
<td id="Last_name"></td>
<td id="Gender"></td>
<td id="Dob"></td>
<td id="User_name"></td>
<td id="Password"></td>
</tr>
</table>
</div> <!-- end for class "result" -->
</div><!-- end for class "row" -->
</div><!-- end for class "container" -->
[/html]
Step3 :
Add JavaScript files end of body tag in HTML to improve the performance of our Web application
Add below code in end of HTML body
[javascript]
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="js/jquery.validationEngine-en.js"></script>
<script type="text/javascript" src="js/jquery.validationEngine.js"></script>
<script type="text/javascript" src="js/Save-data-using-Ajax-and-PDO-with-Bootstrap.js"></script>
[/javascript]
Step4 :
We validate all the all fields with jQuery ValidationEngine after that we send the values to server with $.post () function . In Server side we processing those values and insert the data into database by using PDO . we got an JSON format data in Success function of Ajax .Finally, We converted JSON format data into JavaScript Object notation.
Add below code in JavaScript
[javascript]
// JavaScript Document
$(document).ready(function() {
jQuery("#register-form").validationEngine();
var date = new Date();
date.setDate(date.getDate()-1);
$('.datepicker').datepicker({startDate:false,format:'yyyy-mm-dd',autoclose: true,todayHighlight:true});
$("#register-form").on("submit",function(e) {
e.preventDefault();
if($("#register-form").validationEngine('validate')) {
var form_data = $( "form" ).serialize();
$.post( "insert.php",{form_values : form_data},function( data ) {
var Data = jQuery.parseJSON(data);
$(".registration_form").hide(200);
$(".success_msg").show(200,function() {
$(".result").show();
$("td#First_name").html(Data[0].First_name);
$("#Last_name").html(Data[0].Last_name);
$("#Gender").html(Data[0].Gender);
$("#Dob").html(Data[0].Dob);
$("#User_name").html(Data[0].User_name);
$("#Password").html(Data[0].Password);
});
});
} else {
return false;
}
});
});
[/javascript]
Step5 :
We create a users table with nine columns(id(Primary Key),First_name, Last_name, Gender, Dob, User_name, Password, Created_Date, Last _Modified) in save-data-using-ajax-and-pdo-with-bootstrap database to store form values in users table
Create 'users' table
[php]
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`First_name` varchar(255) NOT NULL,
`Last_name` varchar(255) NOT NULL,
`Gender` varchar(20) NOT NULL,
`Dob` date NOT NULL,
`User_name` varchar(255) NOT NULL,
`Password` varchar(100) NOT NULL,
`Created_date` datetime NOT NULL,
`Last_modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
[/php]
Step6 :
We create a db.php file to connect with a database by using PDO .In line 12 we create a PDO object to connect with a database.
Create db.php file
[php]
<?php
$username = "root";
$password = "";
$host = "localhost";
$dbname = "save-data-using-ajax-and-pdo-with-bootstrap";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8",$username, $password ,$options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>
[/php]
Step7 :
We create insert.php file to get the values from client side then Processing the values and inserted into database. Finally , we fetch the inserted data from database by using last_insert_id to give a JSON response to client request.
Create insert.php file
[php]
<?php
if(isset($_POST["form_values"]))
{
$form_data = urldecode($_POST["form_values"]);
preg_match_all('#(\w+)=([^&=]*)(?:&|$)#', $form_data, $matches, PREG_SET_ORDER);
$result = array();
$i = 0;
foreach ($matches as $m) {
list(, $key, $value) = $m;
if (!strlen($value)) {
$i = (int)$key;
} else {
$result[$i][$key] = $value;
}
}
require_once("db.php");
$firstName = $result[0]["firstName"];
$lastName = $result[0]["lastName"];
$gender = $result[0]["gender"];
$dob = $result[0]["dob"];
$userName = ($result[0]["userName"]);
$password = md5($result[0]["passwd"]);
$sql_insert = "INSERT INTO users (First_name, Last_name, Gender, Dob, User_name,Password,Created_date,Last_modified) VALUES (
:firstName,
:lastName,
:gender,
:dob,
:userName,
:password,
:Created_date,
:Last_modified
)";
try
{
$query_insert = $db->prepare( $sql_insert );
$result_insert = $query_insert -> execute(array(
':firstName'=>$firstName,
':lastName'=>$lastName,
':gender'=>$gender,
':dob'=>$dob,
':userName'=>$userName,
':password'=>$password,
':Created_date'=>date("Y-m-d H:i:s"),
':Last_modified'=>date("Y-m-d H:i:s")));
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
if($result_insert) {
$last_insert_id = $db->lastInsertId();
$sql_select = "SELECT
First_name,
Last_name,
Gender,
Dob,
User_name,
Password,
Created_date,
Last_modified
FROM users
WHERE
id = :id";
try
{
$query_select = $db->prepare( $sql_select );
$query_select->execute(array(':id'=>$last_insert_id));
$results=$query_select->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
//echo "You are successfully registered.";
} else {
echo "error occured";
}
}
?>
[/php]