Ajax and PHP

AJAX in a word… SWEET! I love it. AJAX stands for Asynchronous JavaScript and XML. Basically it allows your web page to load content AFTER the web page has already loaded. This comes in handy when you want to perform actions on a web page or change content but don’t want to reload the entire page to do it.

Let’s take an example. You have a dating website with loads of users. Users can view other users’ profile pages. On the profile page it shows a user’s information, including whether that user is online right now or not. Wouldn’t it be cool if you could keep the page open for a while and the user you are looking at logs on and at that moment it notifies you, all without you having to reload the page? You can accomplish this with the help of some AJAX.

Let’s start by looking at an HTML code snippet you might include in the User Profile page.

<div id="online_status"></div>

This is the container for the string telling us the user’s online status. But wait… the div doesn’t have anything in it… yet. This is where our AJAX comes in. Add the following below your div.

<script type="text/javascript">
    function getOnlineStatus(user_id){
        // Make the AJAX call
        ajax("get-online-status.php", handleOnlineStatusRequest);
        // Javascript code continues, even while the AJAX call is being made.
        // Something could execute here ...
        // and here ...
        // ... all while we wait for a response
    function handleOnlineStatusRequest(response_text){
        // This function is called by our 'ajax' function when the AJAX request has completed successfully.
        // 'response_text' contains any text that was sent back to us from the 'get-online-status.php' page.
        // Fill in the 'online_status' div with the response text from our AJAX call
        document.getElementById('online_status').innerHTML = response_text;
		// Set the next timeout.  We will check every 10 seconds for a change in the user's status
        setTimeout("getOnlineStatus(1)", 10000);
    // Initialize the AJAX object
    function initXmlHttp(){
        // Standard Initialization
        var tmpxmlHttp;
        try {
            // Firefox, Opera 8.0+, Safari
            tmpxmlHttp = new XMLHttpRequest();
        catch (e) {
            // Internet Explorer
            try {
                tmpxmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            catch (e) {
                try {
                    tmpxmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;
        return tmpxmlHttp;
    // Our AJAX function
    function ajax(url, responseHandler){
        // Create our AJAXy object
        var xmlHttp = initXmlHttp();
        // Handle changes to the object's state
        xmlHttp.onreadystatechange = function(){
            // Is our request complete?
            if (xmlHttp.readyState == 4) {
                // Request is complete (identified by a value of 4) so pass the response text into our handler function
        // Open a connection
        xmlHttp.open("GET", url, true);
        // Make the request
    // Make a request for the user's status

Let’s briefly go over the functions in the order they are called:

  • getOnlineStatus – We pass in an ID of 1 to get the status for user 1.
  • ajax – This function takes a url to our backend file, written in PHP, and the function that will be called when the request has been completed.
  • initXmlHttp – This simply creates an object for us that will perform the AJAX call.
  • handleOnlineStatusRequest – This function is passed the response text from our back end PHP file and places the response text into our online status div.

Now the final piece is the backend script. In this example we will be using PHP. Create a file called get-online-status.php in the same directory where your html file is stored. Copy and paste the following code inside it.

// Get the user ID that was handed to us
$user_id = $_GET['user_id'];
// We'll say the user is online
$online_status = 1;
$online_status_text = $online_status == 1 ? "Online!" : "Offline";
// Output the result text. Anything we output here will be sent back to the requesting page
echo ($online_status_text);

Now our example is complete. This PHP file simply outputs the response text we want, in this case it outputs the string “Online!”. Our JavaScript then takes that string and places it inside our div, letting the user viewing the profile know that the user they are viewing is signed in. The JavaScript will check the status every 10 seconds.

Pretty cool huh! For fun, open the web page, and while it is open set the online status to 0 in your PHP file and save. Check the webpage you have open and within 10 seconds it should change the status to “Offline”.