AJAX Tutorial
|
|
To see how AJAX works, we will develop small AJAX Web Application.
First of all we need some HTML file with forms to input data. This will be one input field where we can write some text. In our case this will be some name. This HTML file we will save under ajax.html name. The code of HTML file can taken from box bellow: (Please note that the text input handle onkeypress event and call to ajax(); function and there is no “Submit” button in HTML form)
-
<html>
-
<body>
-
<input type="text" onkeyup="ajax(this.value);">
-
</br>
-
<div id="result"></div>
-
</body>
-
</html>
The key of each AJAX application is the XMLHttpRequest object. In some browsers we have to use one methods to create the XMLHttpRequest object. In other browser we have to use other method. Because we don’t know what browser use the user we will try each method until we successfully make XMLHttpRequest object.
-
var xmlhttp;
-
try {
-
xmlhttp=new XMLHttpRequest();
-
}
-
catch (e) {
-
try {
-
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
-
}
-
catch (e) {
-
try {
-
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
-
}
-
catch (e) {
-
alert("Your browser does not support AJAX!");
-
return false;
-
}
-
}
-
}
Now some explanation:
First we create variable named xmlhttp were we put the XMLHttpRequest object. Then try to create the object with xmlxttp=new XMLHttpRequest(). This method will work in Firefox, Opera, and Safari browsers. If the method return false fails, then try xmlhttp=new ActiveXObject("Msxml2.XMLHTTP") which is method for Internet Explorer 6.0+, if this method also return false, finaly we try xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") which is method for Internet Explorer 5.5+
If no one of these three methods return the XMLHttpRequest object, we will alert user with message that says – Your browser doesn”t support AJAX!.
When we already have XMLHttpRequest object we have to send the request to the server. This we make with open() and send() methods. The open() method have three parameters. The first parameter sets with which method to send the request (GET or POST). The second parameter sets the URL of the server-side script. The third parameter sets handle method of request – asynchronously true/false. The send() method is exact way to send the request to the server.
After sending a request to the server, we have to receive the data that is returned by the server-side script. This is made with onreadystatechange function. The onreadystatechange function have five states:
0 – The request is not initialized
1 – The request has been set up
2 – The request has been sent
3 – The request is in process
4 – The request is complete
In our code we will check the state and when we have 4 – The request is complete for onreadystatechange function we will display result for the user. Now lets assemble all of this and update our ajax.html file:
-
<html>
-
<script type="text/javascript">
-
function ajax(str) {
-
var xmlhttp;
-
try {
-
xmlhttp=new XMLHttpRequest();
-
}
-
catch (e) {
-
try {
-
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
-
}
-
catch (e) {
-
try {
-
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
-
}
-
catch (e) {
-
alert("Your browser does not support AJAX!");
-
return false;
-
}
-
}
-
}
-
var url='ajax.php?data='+str;
-
xmlhttp.onreadystatechange=function() {
-
if(xmlhttp.readyState==4) {
-
document.getElementById('result').innerHTML=xmlhttp.responseText;
-
}
-
}
-
xmlhttp.open("GET",url,true);
-
xmlhttp.send(null);
-
}
-
</script>
-
<body>
-
<input type="text" onkeyup="ajax(this.value);">
-
</br>
-
<div id="result"></div>
-
</body>
-
</html>
Next we have to prepare small PHP file. This is the server-side file where the requests will sends and AJAX function will get the result. We use some PHP array for store the names. And will check for match with stristr() case-insensitive function. You can use the code below:
-
<?php
-
header("Cache-Control: no-cache, must-revalidate");
-
header("Expires: Mon, 1 Jan 1990 01:00:00 GMT");
-
$names=array(John,Will,Kelly,Diana,Robert,Nina,George,Michael,Clint,Debora,Nick,Jeff,Kevin,Samuel,David,Peter,Patrick,Quest,Silvia,Umbro,William,Zita,Yantra,Xena,Albert,Ulrich);
-
for ($i=0;$i<count($names);$i++) {
-
if (stristr($names[$i], $_GET[data])) {
-
$result.=$names[$i]."\n";
-
}
-
}
-
echo nl2br($result);
-
?>
And now let see how our AJAX application works. Please type some name, for example Nina:


tnx
it is so usefull
hi, this is very useful for me. thank you for providing this.
regards
http://www.srisoftwarez.com
very useful.tnx
An average one.
Thanks for share your knowledge.
helpful
Its very clear explanation. very useful thank u very much
Can somebody Help me, i have a shopping cart project. I like to change the quantity into AJAX. when i change the quantity, automatically chnage the price total. Please Help me. Thank you.
Please Help me
include(“./storescript/config.php”);
$cartOutput=”";
$cartTotal=”";
$paypal_checkout_Btn=”;
$product_id_array=”;
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])< 1) {
$cartOutput=" Your Shooping Cart is Empty “;
}else{
//Start Paypal button
$paypal_checkout_Btn.=’
‘;
//Start Foreach Loop
$i=0;
foreach($_SESSION["cart_array"] as $each_item){
$item_id=$each_item['item_id'];
$sql=mysql_query(“SELECT * FROM products WHERE id=’$item_id’ LIMIT 1″);
while($row=mysql_fetch_array($sql)){
$product_name=$row['product_name'];
$price=$row['price'];
$details=$row['details'];
}
$price_total=$price*$each_item['quantity'];
$cartTotal=$price_total + $cartTotal;
//Start Dynamic Checkout Button assembly
$x=$i+1;
$paypal_checkout_Btn.=’
‘;
//Create Product Array Variable
$product_id_array=”$item_id-”.$each_item['quantity'].”,”;
//Dyanamic Table Assembly
$cartOutput.=”;
$cartOutput.=’‘.$product_name.’‘;
$cartOutput.=”.$details.”;
$cartOutput.=’$’.$price.”;
/*$cartOutput.=’
‘;*/
$cartOutput.=”;
$cartOutput.=”.$price_total.”;
$cartOutput.=”;
$cartOutput.=”;
$i++;
}
$cartTotal=’Cart Total:$’.$cartTotal.”;
$paypal_checkout_Btn.=’
‘;
}
?>
This is my PHP code, Can Somebody Help me
What is not working? Can you post a link to the page? you can add me in skype : stefan.batanov so i can try to help
i already add you
Hi Joener, I’m back from my vacation. I wanted to check if the script worked for you? I will post a tutorial for what I wrote for you but if you have added some changes it will be good to share them with everyone. Waiting your reply
Re-writing an article 2 or 3 times can get pretty boring. So u really have to be up for it…or pay a bundle to outsource!