Insert record through ajax into database

we have created 5 files for insert record through Ajax into database.
(i) Index.php
(ii) response-file.php
(iii) connection.php
(iv) student.sql
(v) jquery-1.11.2.min.js
insert_record_through_ajax

Now you enter the student name and select the class, after that click the save button for saving data into database.

Note:- you can download code from this
rar_image

(i) index.php:- file which has html form, ajax function and include jquery library file.

Note:- For insert, update and delete record, we should use POST method not GET method.
[php]
<html>
<head>
<script src="jquery-1.11.2.min.js"></script>
<script>
function Ajaxfun() {
var stuname = $(‘#stuname’).val();
var stuclass = $(‘#stuclass’).val();
$.ajax({

// The URL for the request
url : "response-file.php",

// The data to send (will be converted to a query string)
data : {
sname : stuname,
sclass : stuclass
},

// Whether this is a POST or GET request
type : "POST",

// Code to run if the request succeeds;
// the response is passed to the function
success : function(response) {
//alert(response);
$("#ajaxDiv").html(response);
},
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error : function(xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
},
});

}
</script>
</head>
<body>
<form name="add_stu_record" id="add_stu_record">
<div style="width:400px; background-color:#e9eaed">
<div align="center"><h3>Insert Record through Ajax</h3></div>

<div>
<div style="float: left;width:30%">
Student Name
</div>
<div style="float: left;width:70%">
<input type="text" name="stuname" id="stuname" />
</div>
</div>
<div style="height: 5px; clear: both"></div>
<div>
<div style="float: left;width:30%">
Student Class
</div>
<div style="float: left;width:70%">
<select name="stuclass" id="stuclass">
<option value="">Select Class</option>
<option value="bca">BCA</option>
<option value="mca">MCA</option>
<option value="btech">Btech</option>
<option value="bba">BBA</option>
<option value="mba">MBA</option>
</select>
</div>
</div>
<div style="clear: both; height:5px;"></div>
<div align="center" onclick="Ajaxfun()">
<input type="button" name="getValue" value="Save" />
</div>
<div style="clear: both;"></div>
<div id="ajaxDiv"></div>
<div style="clear: both; height:5px;"></div>
</form>
</div>
</body>
</html>
[/php]

(ii) response-file.php:- which has include database connection file and database query.

[php]
<?php
include (‘connection.php’);
$sname = mysql_real_escape_string($_REQUEST[‘sname’]);
$sclass = mysql_real_escape_string($_REQUEST[‘sclass’]);
$errmsg = "";
$err_count = 0;

if ($sname == ”) {
$errmsg .= "<div style=’color:#ff0000′;>Please enter student name!</div>";
$err_count++;
}
if ($sclass == ”) {
$errmsg .= "<div style=’color:#ff0000′;>Please select the student class!</div>";
$err_count++;
}
if ($err_count == 0) {
$query = "insert into stuinfo(stu_name,stu_class) values(‘".$sname."’,’".$sclass."’)";
$result=mysql_query($query);
if(!$result)
{
echo ‘Error: Record is not save’ ;
}
else{
echo "<div style=’color:#008000′;>Insert record save successfully</div>";
}
} else {
echo $errmsg;
}
?>
[/php]

(iii) connection.php:- which is include in the response-file.php

[php]
<?php
$host_name = "localhost";
$user_name = "root";
$password = "";
$database_name = "student";
$conn = mysql_connect($host_name, $user_name, $password);
if (!$conn) {
die(‘server is not connect’);
} else {
mysql_select_db($database_name, $conn);
}
?>
[/php]

(iv) student.sql:- upload in to mysql-database.

(v) jquery-1.11.2.min.js:- this jquery library include in the index.php file.

Note:- For update and delete record through ajax is very simple, you should change only query into response-file.php

Fetch Record through Ajax from database

we have created 5 files for fetch record through Ajax from database.
(i) Index.php
(ii) response-file.php
(iii) connection.php
(iv) employee.sql
(v) jquery-1.11.2.min.js

fetch_record_through_ajax

Note:- you can download code from this

rar_image

(i) index.php:- file which has html form, ajax function and include jquery library file.

Note:- For fetch record, we should use GET method.
[php]
<html>
<head>
<script src="jquery-1.11.2.min.js"></script>
<script>
function Ajaxfun() {
var username = $(‘#uname’).val();
$.ajax({

// The URL for the request
url : "response-file.php",

// The data to send (will be converted to a query string)
data : {
uname : username
},

// Whether this is a POST or GET request
type : "GET",

// Code to run if the request succeeds;
// the response is passed to the function
success : function(response) {
//alert(response);
$("#ajaxDiv").html(response);
},
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error : function(xhr, status, errorThrown) {
alert("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
},
});

}
</script>
</head>
<body>
<form>
<div style="width:400px; background-color:#e9eaed">
<div>
<div style="float: left;width:30%">
Select Name
</div>
<div style="float: left;width:70%">
<select name="uname" id="uname">
<option value="">Select Name</option>
<option value="John">John</option>
<option value="Tony">Tony</option>
<option value="Leela">Leela</option>
<option value="Robert">Robert</option>
</select>
</div>
</div>
<div style="clear: both; height:5px;"></div>
<div align="center" onclick="Ajaxfun()">
<input type="button" name="getValue" value="Get Value"/>
</div>
<div style="clear: both;"></div>
<div id="ajaxDiv"></div>
</form>
</div>
</body>
</html>
[/php]
(ii) response-file.php:- which has include database connection file and database query.
[php]
<?php
include (‘connection.php’);
$uname = mysql_real_escape_string($_REQUEST[‘uname’]);
$errmsg = "";
$err_count = 0;

if ($uname == ”) {
$errmsg .= "Please select the uname";
$err_count++;
}
if ($err_count == 0) {
$query = mysql_query("select * from emp where emp_name=’" . $uname . "’");
while ($results = mysql_fetch_assoc($query)) {
echo $results[’emp_name’] . ‘ is a ‘ . $results[’emp_desgination’] . ‘ and monthly income is ‘ . $results[’emp_salary’];
}

} else {
echo $errmsg;
}
?>
[/php]

(iii) connection.php:- which is include in the response-file.php
[php]
<?php
$host_name = "localhost";
$user_name = "root";
$password = "";
$database_name = "employee";
$conn = mysql_connect($host_name, $user_name, $password);
if (!$conn) {
die(‘server is not connect’);
} else {
mysql_select_db($database_name, $conn);
}
?>
[/php]
(iv) employee.sql:- upload in to mysql-database.

(v) jquery-1.11.2.min.js:- this jquery library include in the index.php file.

jQuery with Ajax

there are 5 different functions that used to make Ajax call to page and to fetch data. I am going to discuss about those five functions one by one. Following is a list of the five functions available in JQuery library to make an Ajax call.
(1) $.load()
(2) $.getJson()
(3) $.GET()
(4) $.POST()
(5) $.Ajax()

(1) $.load():- this method is to loading HTML content on your web page asynchronously.

$.load(htmlPageUrl):- If you use $.load(htmlPageUrl) passing only the URL of the HTML document as argument, the entire content of the HTML document is loaded into the calling page.

example:- In this eg. we load test.html file data into result div.
[php]
$( "#result" ).load( "test.html" );
[/php]

$.load(htmlPageUrl fragmentIdentifier):- which exactly targets the bit of content I intend to retrieve.

example:- In this eg. we load container div data of test.html file into result div.
[php]
$( "#result" ).load( "test.html #container" );
[/php]

(2) $.getJson():- This method allows to get json data by making ajax call to page. This method allows only to pass the parameter by get method. This method treats the response as Json.

Note:- (i) Only sends data using get method, post is not allowed.
(ii) Treats the response data as Json only.

Example:- Load the JSON data from test.js and access a name from the returned JSON data.
[php]
$.getJSON( "test.js", function( json ) {
console.log( "JSON Data: " + json.users[ 3 ].name );
});
[/php]

(3) $.get():- Allow to make ajax request with the get method. It handles the response of many formats including xml, html, text, script, json, and jonsp.

Note:- (i) Sends data using get method only.
(ii) Can handle any type of the response data.

Example:- Get the test.php page contents, which has been returned in json format (“John”,”time”=>”2pm” ) ); ?>), and add it to the page.
[php]
$.get( "test.php", function( data ) {
$( "body" )
.append( "Name: " + data.name ) // John
.append( "Time: " + data.time ); // 2pm
}, "json" );
[/php]

(4) $.post():- Allows to make ajax request with the post method. It handles the response of many formats including xml, html, text, script, json, and jonsp. post does same as get but just sends data using post method.

Note:- (i) Sends data using post method only.
(ii) Can handle any type of the response data.

Example:- Post to the test.php page and get content which has been returned in json format (“John”,”time”=>”2pm”)); ?>).
[php]
$.post( "test.php", { func: "getNameAndTime" }, function( data ) {
console.log( data.name ); // John
console.log( data.time ); // 2pm
}, "json");
[/php]

(5) $.ajax():- Allows to make the ajax call. This method provides more control than all other methods we have seen. You can figure out the difference by checking the list of parameters.

Note:- (i) Provides more control on the data sending and on response data.
(ii) Allows to handle error occur during call.
(iii) Allows to handle data if the call to ajax page is successful.

Example:-
[php]
var ajaxUrl = "Json.htm";
$("#btnAjax").click(function () {
$("#dvAjax").html(ajax_load);

$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: "", //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (json) {//On Successful service call
var result = json.name;
$("#dvAjax").html(result);
},
error: ServiceFailed // When Service call fails
});

return false;
});
[/php]
In the above code, you can see all the parameters and comments related to each parameter describe the purpose of each one. Firebug shows the called page return json data and Ajax function treats the respose as Json because in code datatype = json.

Ajax Example

In this example we create two files
(1) is index.php, which is client side file.
(2) is ajax_results.php, which is server side file.

You can download code from this url

rar_image

In index.php file
[php]
<html>
<head>
<script>
function Ajaxfun(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}

// Now get the value from user name, user sex and pass it to
// server script.
var uname = document.getElementById(‘uname’).value;
var usex = document.getElementById(‘usex’).value;

var queryString = "?uname=" + uname ;
queryString += "&usex=" + usex;
ajaxRequest.open("GET", "ajax-results.php" + queryString, true);
ajaxRequest.send(null);

// Create a function that will receive data
// sent from the server and will show data on the ajax div.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById(‘ajaxDiv’);
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}

}</script>
</head>
<body>
<form>
<div>
<div style="float: left;width:30%">
Your Name
</div>
<div style="float: left;width:70%">
<input type="text" id="uname" />
</div>
</div>
<div>
<div style="float: left;width:30%">
Your Sex
</div>
<div style="float: left;width:70%">
<select name="usex" id="usex">
<option value="">Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<div style="clear: both"></div>
<div align="center" onClick="Ajaxfun()">
<span style="background-color:#3a5795; color:#fff; cursor: pointer;">Get</span>
</div>
<div style="clear: both"></div>
<div id="ajaxDiv"></div>
</form>
</body>
</html>
[/php]
In ajax_request.php
[php]
<?php
$uname=$_REQUEST[‘uname’];
$usex=$_REQUEST[‘usex’];
$errmsg="";
$err_count=0;
if($uname==”)
{
$errmsg .="Please write the name";
$err_count++;
}
if($usex ==”)
{
$errmsg .="Please select the sex";
$err_count++;
}
if($err_count==0)
{
echo "Hi, your name is $uname and sex is $usex";
}else{
echo $errmsg;
}
?>
[/php]
Output is:-
ajax_output

XMLHttpRequest

An Object of XMLHttpRequest is used to send HTTP or HTTPS requests to a web server and load the server response data back, without reloading the page.

How to create an XMLHttpRequest Object?
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax:- variable=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
Syntax:- variable=new ActiveXObject(“Microsoft.XMLHTTP”);

Properties of XMLHttpRequest object

(1) onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes
(2) readyState
represents the state of the request. It ranges from 0 to 4.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
(3) status
200: “OK”
404: Page not found

Note:- When readyState is 4 and status is 200, the response is ready.

Methods of XMLHttpRequest object
To send a Request To a Server, with the help of the open() and send() methods of the XMLHttpRequest object.

open(method,url,async)
Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)
Sends the request off to the server.
string: Only used for POST requests.

Example:- xmlhttp.open(“GET”,”getting_ajax_info.php”,true);
xmlhttp.send();

How Ajax Works?

At the heart of Ajax is the ability to communicate with a Web server asynchronously without taking away the user’s ability to interact with the page. The XMLHttpRequest is what makes this possible. Ajax makes it possible to update a page without a refresh.
By Ajax, we can refresh a particular DOM object without refreshing the full page. Let’s see now what actually happens when a user submits a request:
Ajaxflow1

In the above image we define 6 steps.
(1) User sends a request from the UI and a javascript call.
(2) It goes to XMLHttpRequest object.
(3) HTTP Request is sent to the server by XMLHttpRequest object.
(4) Web Server interacts with the database using JSP, PHP, Servlet, ASP.net etc and Data is retrieved.
(5) Server sends XML data or JSON data to the XMLHttpRequest callback function.
(6) HTML and CSS data is displayed on the browser.

Ajax Technologies

AJAX cannot work independently. It is used in combination with other technologies.
(i) XML or JSON
(ii) XMLHttpRequest
(iii) DOM
(iv) HTML/XHTML and CSS
(v) JavaScript

we can say this combination is Ajax Technologies.

(i) XML or JSON:- For carrying data to and from server. JSON (Javascript Object Notation) is like XML but short and faster than XML.

(ii) XMLHttpRequest:- The XMLHttpRequest object for asynchronous communication with client and server.

(iii) DOM:- The Document Object Model (DOM) for dynamic display of and interaction with data.

(iv) HTML/XHTML and CSS:- It is mainly used for presentation.

(v) JavaScript:- JavaScript to bring these technologies together.

what is Ajax?

AJAX stands for Asynchronous JavaScript and XML.
AJAX is the way of exchanging data with a server, and updating parts of a web page – without reloading the whole page.
Example:- Ajax is used many web application like google, facebook, yahoo, twitter, youtube etc.

Why use Ajax?
We will explain through example, Traditionally webpages required reloading to update their content. For web-based email this meant that users had to manually reload their inbox to check and see if they had new mail. This had huge drawbacks: it was slow and it required user input. When the user reloaded their inbox, the server had to reconstruct the entire web page and resend all of the HTML, CSS, JavaScript, as well as the user’s email. This was hugely inefficient. Ideally, the server should only have to send the user’s new messages, not the entire page through Ajax.

Difference between Synchronous and Asynchronous?
Synchronous means that data is sent in a sequence and Asynchronous means that data is not sent in a sequence.
OR
Synchronous waits for each operation to complete, after that only it executes the next operation. Asynchronous never waits for each operation to complete, rather it executes all operations in the first GO only.