Ajax:
What is AJAX?
AJAX = Asynchronous JavaScript And XML.
AJAX is not a programming language.
AJAX just uses a combination of:
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.
How AJAX Works
1. An event occurs in a web page (the page is loaded, a button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript
Advantages of AJAX:
AJAX Advantages
AJAX Concept
Before you starting AJAX you'll need to have a strong knowledge of JavaScript. AJAX is not a difficult, you can easy
implement AJAX in a meaningful manner. Some IDE are help us to implement AJAX.
Speed
Reduce the server traffic in both side request. Also reducing the time consuming on both side response.
Interaction
AJAX is much responsive, whole page(small amount of) data transfer at a time.
XMLHttpRequest
XMLHttpRequest has an important role in the Ajax web development technique. XMLHttpRequest is special
JavaScript object that was designed by Microsoft. XMLHttpRequest object call as a asynchronous HTTP request to
the Server for transferring data both side. It's used for making requests to the non-Ajax pages.
Asynchronous calls
AJAX make asynchronous calls to a web server. This means client browsers are avoid waiting for all data arrive
before start the rendering.
Form Validation
This is the biggest advantage. Form are common element in web page. Validation should be instant and properly,
AJAX gives you all of that, and more.
Bandwidth Usage
No require to completely reload page again. AJAX is improve the speed and performance. Fetching data from
database and storing data into database perform background without reloading page.
XMLHttpRequest Object:
Create an XMLHttpRequest Object:
Syntax:
variable = new XMLHttpRequest();
XMLHttpRequest Object properties:
Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
open(method, url, async) Specifies the type of request
method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
Status 200: "OK"
403: "Forbidden"
404: "Page not found"
Server Response Properties
Property Description
responseText get the response data as a string
responseXML get the response data as XML data
Ajax Example:
Compute1.html:
<html>
<head>
<script>
var a,b,url;
function fu()
{
a=document.getElementById("t1").value;
b=document.getElementById("t2").value;
url="calc1.php?v1="+a+"&v2="+b;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
function stateChanged()
{
//document.writeln(xmlhttp.readyState);
if (xmlhttp.readyState==4)
{
document.getElementById("t3").value=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<form>
<label> First Value:</label><input type="text" id="t1"/><br><br>
<label>Last Value:</label><input type="text" id="t2"/><br><br>
<label>Last Value:</label><input type="text" id="t3" name="v3"/><br><br>
<input type="button" value="click" onclick="fu()"/>
</form>
</body>
</html>
Calc1.php:
<?php
$x=$_GET['v1'];
$y=$_GET['v2'];
$z=$x+$y;
echo $z;
?>
AJAX Database:
Example:
Client.html:
<html>
<head>
<title></title>
<script>
var a,b,url;
function fu()
{
//alert("hai");
a=document.getElementById("t1").value;
b=document.getElementById("t2").value;
url="server.php?v1="+a+"&v2="+b;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
function stateChanged()
{
//document.writeln(xmlhttp.readyState);
if (xmlhttp.readyState==4)
{
//alert("by");
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<form>
<label>ID</label><input type="text" id="t1"><br><br>
<label>NAME</label><input type="text" id="t2"><br><br>
<button type="button" onclick="fu()">submit</button>
</form>
<div id="result">
</div>
</body>
</html>
Server.php
<html>
<head>
<title></title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>NAME</th>
</tr>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
$id=(int)$_GET["v1"];
$uname=$_GET["v2"];
//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to insert into table
$sql = "insert into myguest(id,firstname)values($id,'$uname')";
if ($conn->query($sql) === TRUE)
{
$sql = "SELECT id, firstname FROM myguest";
$result = $conn->query($sql);
if ($result->num_rows> 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>".$row["id"]."</td>";
echo "<td>".$row["firstname"]."</td>";
echo "</tr>";
}
}
else
{
echo "0 results";
}
}
else
{
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
</table>
</body>
</html>
AJAX with XML
Example:
Ajaxxml.html:
<html>
<head>
<title></title>
<script>
var a,b,url,xmldoc;
function fu()
{
url="books.xml";
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
function stateChanged()
{
//document.writeln(xmlhttp.readyState);
if (xmlhttp.readyState==4)
{
xmldoc=xmlhttp.responseXML;
var x=xmldoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
alert(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
}
}
}
}
</script>
</head>
<body>
<button type="button" onclick="fu()">submit</button>
</body>
</html>
Books.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Edited by XMLSpy -->
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>