So, we now have a pretty common appearance of Web 2.0 across the world, but what exactly is Web 2.0? Really there are not set definitions or rules behind Web 2.0, it is just a way of describing a new set of technologies that have recreated the web. One of the more exciting and cool technologies is asynchronous server communication, sometimes referred as AJAX. With AJAX you don't need to refresh a page to get information from the server. You can call server pages and get the response, all with Javascript. In this tutorial I will show you the most basic way to get a response from a PHP script.
This tutorial will cover just the basics with AJAX, and we will start with the base object you need: a XMLHTTP Javascript object. With this object you call a server-side script and get the response back. Most browsers use the same Javascript object, but of course Microsoft has to be different, so they require their own. The following function will return the correct object:
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
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;
}
}
}
return xmlHttp;
}
This code will, again, return an XMLHTTP object to use in our Javascript. What is going to happen is that we are going to use this object to make an HTTP request through Javascript. When we get a response back, we will simply place it in the page, nothing fancy. In order to make the request we use the following code:
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
The key to this whole process is using the XMLHTTP member readyState, which is pretty much exactly what it sounds like. The readyState corresponds to the state of the object itself, which can be anything from Uninitialized to Loaded. In the case of an AJAX request, we wait for the readyState to be 4, which is the maximum value and tells us that all the data to be loaded from the request is. So when the readyState is 4, the request is done and the data is ready for display.
Once you take care of catching the readyState, you need to make the actual request, using the open() and send() methods. The open method is what we use to set up the request. It takes in a request type (ie "post" or "get"), the page URL, and a boolean value indicating wheather we are making an asynchronous call or not. In this case we are, so it is true. So to set up the open() call, we use GET, ajax.php for the url, and set the asynchronous boolean to true.
After you have your open() method all set up, you need to call send() to make the actual request. The send() method makes the request, sending all the arguments you give it. For this case, we are sending nothing, so the arguments are null. When we get the response back, we have to do something with the data sent back. We use the HandleResponse() function to display the information sent back, when the readyState is 4 of course. The HandleResponse() function look like so:
{
document.getElementById('ResponseDiv').innerHTML = response;
}
All this function does is take the response from the request and puts it in a div on our page. Now, that is all our Javascript, which works just fine all in one file, which we will call ajax.js. Now that we have our Javascript, we need to make our ajax.php file, with is one monsterous file, full of complex code:
echo "This is a php response to your request!!!!!!";
?>
Yep, that is it. One echo statement is all we really need for this tutorial. The concept is that all we need to do is send something back to the XMLHTTP object. In the simplest form, this is just some text, where PHP's echo statement works perfectly. This will return our statement back and Javascript will display it on the page. But what about the page eh?
The page in question can really be anything as long as it calls the MakeRequest() method in our javascript file. In our case we will make a simple index.html page that will have a button and a div. The code will look something like:
<html>
<head>
<script type='text/javascript' src='ajax.js'></script>
<title>PHP AJAX Example</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
The HTML itself is very simple and easy to understand, and this page is less than basic. All it has is a button that calls our MakeRequest() method and the Response div that holds the response. To give you a better example :
As you can see, the page did not refresh, yet we got our echo from the php script. Asynchronous communications are so wondrous, aren't they? Now all you have to do is fill in the PHP file with something a little more useful. Some of the more complex stuff includes sending whole objects to Javascript, but that is for another time. For now, this tutorial is all wrapped up. Just Remember that whenever you need coding help, just switch on the code ;)
06/04/2008 - 10:47
Really good work. I found a lot of profound information which can help me to go on.
06/09/2008 - 12:52
Hi. There is a post on Ajaxian which says we should limit the try/catch statements on our JS. I know this is just a dummie sample and it wont make a lot of different, but, maybe it would be nicier to use a simple if instead of try/catch for an application that does a lot of requests, having to create several instances of XmlHttpRequest object. I use something like this:
var xmlObj;
if('Microsoft Internet Explorer' == window.navigator.appName) {
xmlObj = new ActiveXObject("Microsoft.XMLDOM");
} else {
// other browsers
xmlObj = new XMLHttpRequest();
}
xmlObj.async="false";
return xmlObj;
};
03/28/2009 - 02:10
hey this is not working in IE 6 :(
04/14/2009 - 04:13
change ("Microsoft.XMLDOM") to ("Microsoft.XMLHTTP") to make it works..tested in IE6
06/11/2008 - 05:23
Good post. Thank you. But why just not use the MS AJAX components? There're 3 JS files that need to be included into the page and you have pretty well designed, cross-platform AJAX engine. I was successfully used it in projects written in PHP and other languages, hosted on Apache.
06/30/2008 - 11:59
Nice info
thanks
07/01/2008 - 06:43
This is great! I haven't seen something so simple and so easy to understand as yours in the recent past.
07/16/2008 - 19:40
Nice and simple for conceptual purposes, and I like that you had the server send back a response, unlike this tutorial: http://www.ajaxf1.com/tutorial/ajax-php.html
But how about something useful, like where the server tries to return a php array? You said another time, now do it! ;P
08/26/2008 - 15:39
Nice.
Thanks!
08/29/2008 - 10:36
Thanks for writing a easy but in some ways comprehensive example.
Best Regards,
Randy
08/29/2008 - 18:30
This is amazing info! I set up a page testing this in five minutes, and it worked -
Plus I spiced it up by returning data from a mysql db on the onClick - which I thought was impossible, but is wasn't, and it's really really awesome.
Thanks a lot!
09/24/2008 - 01:07
AJAX Really made simple.
Lot simpler than lot of frameworks. Thanks A Lot.
10/01/2008 - 23:11
php ajax learn
10/03/2008 - 12:25
Great Job !!
10/07/2008 - 21:52
GREAT!!!!!
11/17/2008 - 09:00
gooooood
11/26/2008 - 05:17
This is really very good article on AJAX. useful and elementary but powerful
11/28/2008 - 12:14
Great, Simple yet very effective, just built a small calculator using it.
12/09/2008 - 03:52
I been meaning to look into AJAX a while ago and if I knew it was as easy at that I would have actually done it long before now.
Congratulations on a very novice friendly article!
12/14/2008 - 20:30
Terrific!!
12/15/2008 - 10:32
Another interesting approach of integrating PHP and AJAX:
http://lionframework.blogspot.com/2008/12/ajax-was-never-easier.html
03/28/2009 - 01:42
hey this blog is not found :(
09/01/2009 - 17:48
it's at http://www.lionframework.org/blog/2009/02/ajax-was-never-easier/
12/22/2008 - 18:17
awesome, simple and to the point.
12/24/2008 - 00:27
Really good and very helpfull
thanks
06/17/2009 - 13:29
You may need to change line:
xmlHttp.open("GET", "ajax.php", true);to:
xmlHttp.open("GET", "ajax.php" + Math.random(), true);in order to get it to load from the server every time instead of cache. Only needed if the content of the responce changes with each request.
06/17/2009 - 13:30
Correction:
xmlHttp.open("GET", "ajax.php?" + Math.random(), true);Note the "?"
06/17/2009 - 15:54
Good point, that is one way to handle it. I think setting the http header
cache-controltono-cachewould also work.07/15/2009 - 03:29
Hi.
Thanks for the article.
Nice and simple, But I keep getting this error:
Error: no element found
Line: 4, Column: 3
Source Code:
?>
I have also made the ajax.php file to be:
<?php header("Content-Type: plain/text");
echo "This is a php response to your request!!!!!!";
?>
any thoughts?
Thanks
12/08/2009 - 15:10
Did you ever find a solution? I'm having the same problem and cannot figure out what it is. I tried everything suggested on various forums.
09/25/2009 - 02:32
Hi
when i click button, i called php file through ajax. In that php file i wrote like this
alert('sdf');
<?php
echo "This is a php response to your request!!!!!!";
?>
after getting response i load content into div element, now i get result only in the echo statement but not alert in the javascript.
Please help me!
10/30/2009 - 11:36
Sweet! Simplest tutorial I have found.
01/06/2010 - 07:18
hi good article but some error
01/06/2010 - 07:21
Put Perfect Code Of AjAx
01/27/2010 - 01:41
Nice & simple tutorial. Thanks
02/02/2010 - 16:41
I tried your code. It works in same domain but not cross-domain. How can I make it works?
03/12/2010 - 00:22
Thanks for writing a easy but in some ways comprehensive example.
Best Regards,
karn
04/25/2010 - 19:48
let try to be serious
05/18/2010 - 00:28
hi , i tried tne above code in facebook app. but it dosent return echo statement?
06/29/2010 - 02:47
ajax.js
pleas give me this file
06/29/2010 - 08:49
The link to this file is at the bottom of the post, under Simple_Ajax_Example.js.
07/09/2010 - 01:23
Nice and simple for conceptual purposes, and I like that you had the server send back a response, But how about something useful, like where the server tries to return a php array? You said another time, now do it! ;P
08/04/2010 - 02:00
See here for supported languages.
Javascript must be enabled to submit anonymous comments - or you can login.
Add Comment
[language] [/language]
Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]
See here for supported languages.
Javascript must be enabled to submit anonymous comments - or you can login.