Dirk Bertels

The greatest malfunction of spirit
is to believe things (Louis Pasteur)

Using Ajax and PHP

Index

Introduction
Where to start
Example 1: Server Time
Example 2: Server variables
Example 3: Loading panels into your web page asynchronously
Leave your comments

Introduction

All heartened by my newly acquired ability to display code in full colours (see more on that in my Calender Page), I would like to illustrate some of my favourite Ajax - PHP applications. Ajax is the acronym for Asynchronous Javascript and XML and in essence is just a Javascript subset that enables one to communicate with the server in the background.

Ajax is truly the mother of what now has come to be called Web 2. Its main feature lies in the way it interacts with the server in a asynchronous manner.

For example, say you want to implement a commenting system on your website. Ajax being asynchronous will enable people to add comments 'on the fly' i.e. they don't have to wait for the page to reload as all that stuff will be handled in the background. You can view - and try out - such a commenting system at the end of this page.

The purpose of this article is to illustrate the capabilities of this technique by gradually going through some examples which you can try out for yourself on this very page.

back to index

Where to start

There's literally thousands of articles on ajax on the web - some of them very good. After countless hours of searching, I did come up with some very good links.
First and foremost there is the Mastering Ajax Tutorials (some 11 of them) on the IBM DeveloperWorks website. IBM has some seriously good tutorials on other topics as well.
Another very good article on the IBM site is The Ajax Transport Mechanism. It gives exhaustive examples using each of the transport mechanisms: XMLHTTP, iFrames and Script tags, and for each of these, it gives examples using different formats: Text, XML and Javascript. You will have to sign up for that article but it's well worth the effort, and besides, you will want to read more articles on their site. As an aside, IBM is the organisation that donated Eclipse to the Open Source community.

The main issue with the XMLHTTP mechanism (the one we will address here) is that you can only address the server that sent you the page in the first place. This is obviously done for security reasons. The advantages for using XMLHTTP is simplicity and the fact it handles both GET and POST protocols, which enables you to transfer large amounts of data. Using script tags, you can also address different servers, but the big disadvantage is that you can only use the GET protocol. I hope to handle the script tag method in a later article.

A third excellent source is an ebook I found on the internet. The file is named
OReilly.Ajax.Hacks.Tips.and.Tools.for.Creating.Responsive.Web.Sites.Mar.2006.chm.
It contains a mine of information about different ways of using Ajax. Unfortunately I haven't been able to locate it since ... not sure about its legality, but it exists in book form:

Ajax Hacks 
By Bruce W. Perry 
Publisher: O'Reilly 
Pub Date: March 2006 
Print ISBN-10: 0-596-10169-4 
Print ISBN-13: 978-0-59-610169-5 
Pages: 438 
		

back to index

Example 1: Server Time

The first section (lines 1 to 29) in the following javascript code reveals more than anything that we are going to use Ajax functionality - i.e. create an asynchronous connection. It just creates an XMLHTTPrequest object, details of which depends on the kind of browser we are using. The next section (lines 31 to 38) handles the data returned by the server using XMLHTTPRequest's onReadyStateChange property. When all is well, handleResponse() will be called. And the last section (lines 40 to 42) sends the actual object. The sequence of events is somewhat out of wack in the code, but that seems to be how things are done generally.


function ajaxFunction()
{
    var ajaxRequest;  // The variable that makes Ajax possible!
    try
    {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } 
    catch (e)
    {
        // Internet Explorer Browsers
        try
        {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e) 
        {
            try
            {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e)
            {
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
  
    // Callback function that handles data returned by the server
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState == 4)
        {
            handleResponse(ajaxRequest);
        }
    }
	
	// send the request object to the server
    ajaxRequest.open("GET", "./ajax_files/serverFile.php", true);
    ajaxRequest.send(null); 
}

		

As it stands, not much is going to happen - but it wouldn't take much to make something happen. Let's say we want to ask the server what time it is over there. To do that we first write a server script that does just that. So our serverFile.php file mentioned on line 41 will have the following code:



<?php
echo date("H:i:s"); 
?>

		

So far, nobody's called ajaxFunction() yet, and we still haven't written the handleResponse().
We can call ajaxFunction() from our html page. Just create a form with 2 textfields. The aim is to listen to a change of focus in the first textfield. If the focus changes (like you're moving to another textfield after having added text to it) we call ajaxFunction(). The server then responds and handleResponse() will print the server's response in the second textfield.



<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>

		

The last step is to write handleResponse() called in Listing 1's line 36. We want to stick the response received from the server into the 2nd textfield. This turns out to be another one-liner:



handleResponse(request)
{
    document.myForm.time.value = ajaxRequest.responseText;
}

		

To illustrate this thing, I will now create a javascript file with the ajaxFunction() and handleResponse() and refer to it in this html file, I then will create the php file and stick it on the server and lastly write the html excerpt underneath this paragraph - for you to try out.

... Well I've done all that - here is the form - enter some text into the first field, then leave it and do something like start adding text in the 2nd one.


Enter something :
Time from server:

If your Javascript is enabled, you should see the response from the server(which is located in the USA). Normally we would have to load the whole page again to do such a thing, but I hope you noticed the asynchronicity of Ajax - it was quietly getting the information from the server while you were doing your thing. Obviously, this is a very efficient way to interact with the server since we save a lot of time and bandwidth.

back to index

Example 2: Server variables

But why stop at getting the time from the server, we could for example find out what variables are stored on the server relating to this session. Again, enter something in the first textbox - then start typing in the 2nd textbox.

Enter something :


To implement this, we need a little more code for the server. But to start with, change the html with:



<form name='myForm'>
Enter something: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
<textarea color='120' rows='20' name='info' /></textarea><br />
</form>

		

The javascript function just needs the line in the handleResponse() method changed to:



handleResponse(request)
{
    document.myForm.info.value = ajaxRequest.responseText;
}

		

And the php file needs the following code:



// Set some variables to check
$_POST['name']= "Dicky";
$_POST['ambition']="zilch";

$_GET['getvar1']="mymy";
$_GET['getvar2']="heyhey";

$_COOKIE['cookie1']="rock and roll";
$_COOKIE['cookie2']="is here to stay";


echo "List of Server Variables \n";
display($_SERVER);

echo "List of POST Variables \n";
display($_POST);

echo "List of GET Variables \n";
display($_GET);

echo "List of COOKIE Variables \n";
display($_COOKIE);

echo "List of Environment Variables \n";
display($_ENV);

echo "List of Global Variables \n";
display($GLOBALS);


function display($item)
{
    foreach($item as $key=>$value)
    {
        echo $key . " = " . $value . "\n";
    }
    echo "\n";
}
?>

		

This should give you a taste of how easily Ajax interacts with PHP. PHP in particular has very powerful functions to handle networking. For example, using Ajax it is very easy to send off an email without the user even noticing.

back to index

Example 3: Loading panels into your web page asynchronously

For starters, check out my blog page which I implemented using this method.

The idea is to be able to call at will - pages that are located on the server into your current page. You can insert these at a particular location marked with div tags. The general flow of implementation goes like this:

1 - On the server create a php page named 'panels_ajax.php'. This enables you to load the page whose name you pass into the URL. This is easily done using the one line

			
require('panels/panel_' . $_GET['panel_id'] . '.html');

		

If you call panels_ajax.php passing the name of the file you want into the URL, then the server will send you that file.


2 - On this same server, have the pages you want to load in a folder named 'panels'. For now, we just stick one page in there, named 'panel_01.php'.


3 - The current page needs a little span tag to function as a button that calls panels_ajax.php with the name of the file you want to insert attached. It also needs a location you can insert your panel(s) returned by the server into, like a div tag with an id.


			
<!-- create style for span link -->
<style type="text/css">
.spanLink:visited{ text-decoration:none; color:#293d6b;}
.spanLink:hover{ text-decoration:underline; color:#293d6b;}
.spanLink {color:#293d6b; cursor: pointer}
</style>
<!-- Load Menu Buttons:(only one shown) -->
<span class="spanLink" onclick="loadHTML('panels_ajax.php?panel_id=01', 'panel01')">Load Panel</span>
<!-- Location where the pages will be shown -->
<div id="panel01"></div>

		


4 - Include the Javascript. Previously we could get away with calling Ajax using ajaxFunction() without any parameters. This time we need to pass 2 parameters. So we replace ajaxFunction() with the following code


			
/* GLOBAL VARIABLES */
// request object
var request;
// url of serverfile that Ajax needs to call
var url;
//  id of the location of the calling web site which displays the response from the server
var dest;

/* MAIN FUNCTION.
Creates request object, 
handles the callback, 
and sends request object to the server*/
function ajaxFunction()
{
    try
    {
        // Opera 8.0+, Firefox, Safari
        request = new XMLHttpRequest();
    } 
    catch (e)
    {
        // Internet Explorer Browsers
        try
        {
            request = new ActiveXObject('Msxml2.XMLHTTP');
        } 
        catch (e) 
        {
            try
            {
                request = new ActiveXObject('Microsoft.XMLHTTP');
            } 
            catch (e)
            {
                // Something went wrong
                alert('Your browser broke!');
                return false;
            }
        }
    }
  
    // Callback function that handles data returned by the server
    request.onreadystatechange = function()
    {
        if(request.readyState == 4)
        {
            handleResponse();
        }
    }
    
    
    //Send request to the server
    request.open("GET", url, true);        
    request.send(null); 
}

/* HANDLE THE RESPONSE FROM THE SERVER */
function handleResponse()
{
    var contentDiv = document.getElementById(dest);
    
    if(request.status == 200)
    {
        contentDiv.innerHTML = request.responseText;
    }
    else
    {
        contentDiv.innerHTML = "Error: Status " + request.status;
    }    
}

/* ENTRY FUNCTION FOR EXAMPLE 3 */
function loadHTML(thisUrl, destination)
{
    dest = destination;
    url = thisUrl;
    ajaxFunction();
}

		


5 - Time to demonstrate this. Having worked our way through all this, we create a file 'panel_01.php' that includes a form:


			
<h2>Simple Email Form</h2>
<form action="yourDirectory/contact.php" method="post" id="cForm">
    <fieldset>
        <label for="posName">your name:</label><br />
        <input class="text" type="text" size="25" name="posName" id="posName" />
        <br />
        <label for="posEmail">your email:</label><br />
        <input class="text" type="text" size="25" name="posEmail" id="posEmail" />
        <br />
        <label for="posRegard">regarding:</label><br />
        <input class="text" type="text" size="25" name="posRegard" id="posRegard" />
        <br />
        <label for="posText">message:</label><br />
        <textarea cols="50" rows="5" name="posText" id="posText"></textarea>
        <br />
        <label>
            <input class="submit" type="submit" name="sendContactEmail" 
                    id="sendContactEmail" value=" Send Email " />
        </label>
    </fieldset>
</form>

		


Next we just enter the little html code to try it out. Click this link:  Load Panel



As you can see, this is a very handy feature. Using asynchronous panel loading, we can construct pages dynamically, adding text blocks, commenting forums, email forms, etc as required.
The form's action attribute ensures that the form values are posted to contact.php which then sends the email directly from the server:

<?php
// Change the 4 variables below
$yourName = '[your name]';
$yourEmail = '[your email (the email address you want this email to be send to)]';
$yourSubject = '[your reference, this will prepend the "regarding" value]';
$referringPage = '[enter the full URL of this page]';
// No need to edit below unless you really want to. It's using a simple php mail() function. Use your own if you want
function cleanPosUrl ($str) 
{
    return stripslashes($str);
}

if ( isset($_POST['sendContactEmail']) )
{
    $to = $yourEmail;
    $subject = $yourSubject.': '.$_POST['posRegard'];
    $message = cleanPosUrl($_POST['posText']);
    $headers = "From: ".cleanPosUrl($_POST['posName'])." <".$_POST['posEmail'].">\r\n";
    $headers .= 'To: '.$yourName.' <'.$yourEmail.'>'."\r\n";
    $mailit = mail($to,$subject,$message,$headers);
    if ( @$mailit ) 
    {
        header('Location: '.$referringPage.'?success=true');
    }
    else 
    {
        header('Location: '.$referringPage.'?error=true');
    }
}
?>    
		
		

I did not make this form active however. Mainly because it wouldn't send the email asynchronously, i.e it would do a round trip, refreshing this page on return. There are ways of sending email asynchronously, and we will do exactly that in my next article on Ajax: Asynchronous Commenting with Ajax. This will cover the commenting system used on some of these pages. For now, try it out for yourself by submitting your feedback below.

back to index


Comments