Posted by The Hairiest on 06/04/2008

27 comments
Skill

Simple AJAX - PHP and Javascript

Posted in:

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:

function getXMLHttp()
{
  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:

function MakeRequest()
{
  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:

function HandleResponse(response)
{
  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:

<?php
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:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<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 :

This is a div WITHOUT anything important in it

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 ;)

Outsourcing Company
06/04/2008 - 10:47

Really good work. I found a lot of profound information which can help me to go on.

reply

Thiago
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:

function getXHRObject() {
    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;
};

reply

vijay
03/28/2009 - 02:10

hey this is not working in IE 6 :(

reply

fariq
04/14/2009 - 04:13

change ("Microsoft.XMLDOM") to ("Microsoft.XMLHTTP") to make it works..tested in IE6

reply

Denis Mazourick
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.

reply

Fnfzone
06/30/2008 - 11:59

Nice info

thanks

reply

Janus
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.

reply

Moo
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

reply

Karlis_I
08/26/2008 - 15:39

Nice.
Thanks!

reply

Randy K
08/29/2008 - 10:36

Thanks for writing a easy but in some ways comprehensive example.

Best Regards,
Randy

reply

Assbear
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!

reply

Samy
09/24/2008 - 01:07

AJAX Really made simple.
Lot simpler than lot of frameworks. Thanks A Lot.

reply

Upul Suresh
10/01/2008 - 23:11

php ajax learn

reply

Sam
10/03/2008 - 12:25

Great Job !!

reply

Anonymous
10/07/2008 - 21:52

GREAT!!!!!

reply

Ff
11/17/2008 - 09:00

gooooood

reply

Web designer Kathaperumal
11/26/2008 - 05:17

This is really very good article on AJAX. useful and elementary but powerful

reply

Stu
11/28/2008 - 12:14

Great, Simple yet very effective, just built a small calculator using it.

reply

Christopher Shennan
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!

reply

Anonymous
12/14/2008 - 20:30

Terrific!!

reply

John Secanth
12/15/2008 - 10:32

Another interesting approach of integrating PHP and AJAX:

http://lionframework.blogspot.com/2008/12/ajax-was-never-easier.html

reply

samuel
03/28/2009 - 01:42

hey this blog is not found :(

reply

Defmer
12/22/2008 - 18:17

awesome, simple and to the point.

reply

Shiji
12/24/2008 - 00:27

Really good and very helpfull
thanks

reply

Chris Zahrt
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.

reply

Chris Zahrt
06/17/2009 - 13:30

Correction:
xmlHttp.open("GET", "ajax.php?" + Math.random(), true);

Note the "?"

reply

The Fattest
06/17/2009 - 15:54

Good point, that is one way to handle it. I think setting the http header cache-control to no-cache would also work.

reply

Add Comment

Put code snippets inside language tags:
[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.