PHP Ajax
What is Ajax
AJAX is the acronym for Asynchronous JAvascript and Xml, is not a language rather it is a technique to create interactive or dynamic web page.
AJAX provides XMLHttpRequest objects to interact with the server. AJAX requests small pieces of information, not the whole page using HTTP requests.
AJAX works well with different languages, and it does not require any special server it uses the web page instead.
To know AJAX in detail please visit our website: http://www.roseindia.net/programming-tutorial/Ajax
Following tutorial will help you to learn PHP and AJAX.
In the following example you can see that whenever you enter any alphabet, some suggestions related with that letter will be displayed below the textbox, without refreshing the page, and this is the magic of AJAX. It receives data from the sever in small pieces instead of the whole page.
The example is divided in three parts:
- HTML file: In this file you will create the necessary user interface.
- PHP file: In this file you will create a PHP file which will enlist all the probable names which will be displayed as suggestion.
- AJAX file: This file will be responsible for displaying the dynamic data.
phpAjax.html
<html>
<head>
<script type="text/javascript" src="phpAjax.js"></script>
</head>
<body>
<b><u>Enter Names Below</u></b>
<p/>
<form>
First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
<p>Probable Names are:
</form>
<span id="probable"></span>
</body>
</html>
phpAjax.php
<?php
$a[]="Avishek";
$a[]="Bijay";
$a[]="Chunnilal"; 0
$a[]="Deepak";
$a[]="Dipesh";
$a[]="Elesh"; 1
$a[]="Farha";
$s=$_GET["s"]; 2
if (strlen($s) > 0)
{
$hint=""; 3
for($i=0; $i<count($a); $i++)
{
if (strtolower($s)==strtolower(substr($a[$i],0,strlen($s)))) 4
{
if ($hint=="")
{ 5
$hint=$a[$i];
}
else 6
{
$hint=$hint." , ".$a[$i];
} 7
}
}
} 8
if ($hint == "")
{ 9
$response="Currently Unavailable";
}
else 0
{
$response=$hint;
} 1
echo $response;
?>
phpAjax.js 2
var xmlhttp
function showHint(str)
{ 3
if (str.length==0)
{
document.getElementById("probable").innerHTML=""; 4
return;
}
xmlhttp=GetXmlHttpObject(); 5
if (xmlhttp==null)
{
alert ("Sorry, your browser is compatible!!!"); 6
return;
}
var url="phpAjax.php"; 7
url=url+"?s="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged; 8
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
} 9
function stateChanged()
{
{ 0
document.getElementById("probable").innerHTML=xmlhttp.responseText;
}
} 1
function GetXmlHttpObject()
{
if (window.XMLHttpRequest) 2
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest(); 3
}
if (window.ActiveXObject)
{ 4
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
} 5
return null;
}