One of the most useful new web technologies is AJAX, or Asynchronous JavaScript and XML. In short, AJAX allows you to send and receive server requests without a user having to reload the page. This allows pages to be more dynamic without interrupting the user experience.
AJAX is fairly easy to implement and use effectively, but finding a comprehensive start to finish tutorial for integration with PHP is not quite as easy. To make the task easier, I have put together a simple PHP AJAX framework that is flexible and easy to implement.
The inner workings of AJAX are a mystery for some so I will go over the basics of how our framework will work with PHP.
The PHP AJAX Framework shown below is structured into three parts. The part that stays the same every time is the JavaScript ajaxHelper() function. This is the core of our AJAX functionality. We also need to create two additional JavaScript functions. The code of these functions is different depending on what you want to do. These functions or hooks will be called by the ajaxHelper() function and their names must end in “_init” and “_ajax” which will be explained below.
The ajaxHelper() function
function ajaxHelper(functionName, additionalArgs) {
var xmlHttp;
// Firefox, Opera 8.0+, Safari, SeaMonkey
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Sorry, your browser does not support AJAX.");
return false;
}
}
}
xmlHttp.onreadystatechange=function() {
//The request is complete == state 4
if (xmlHttp.readyState==4) {
var response=xmlHttp.responseText;
//Send reponse to _ajax hook of passed function name
eval(functionName + "_ajax" + '(\'' + response + '\')');
}
}
//Get request string from _setup hook of passed function name
if (additionalArgs !== undefined && additionalArgs.length > 0) {
var requestString = eval(functionName+"_init" + '(' + additionalArgs + ')');
}
else {
var requestString = eval(functionName+"_init" + '()');
}
if (requestString) {
xmlHttp.open("GET", requestString, true);
xmlHttp.send(null);
}
}
The _init and _ajax functions
As stated above, these are functions are hooks, meaning that they will be called dynamically by the ajaxHelper() function depending on the argument you pass it. For example, on a button click you execute the ajaxHelper(’chat_update’) function. The ajaxHelper will call chat_update_init() and then chat_update_ajax() automatically, so you must have them defined. By making them dynamic hooks, you can have many different AJAX calls on the same page but use the same ajaxHelper() function each time. You pass the ajaxHelper() function the first part of the name of your two additional functions (minus the _init and _ajax), which is “chat_update” in the above example.
The _init hook function specifies the name of the PHP file and any arguments to be passed to the ajaxHelper() function. An example _init hook is as follows:
function my_first_try_init() {
//retrieve username from html input box with the id "name_box"
var username = document.getElementById('name_box');
var script = 'myscript.php';
var queryString = "?username=" + username;
return script + queryString;
}
The _ajax function is passed the results of the PHP script specified in the _init hook as a JavaScript variable. Using JavaScript trickery, we can update the page that the user is viewing. You can use the .innerHTML property and change the contents of a div or other element. Or, you could even change the text of input boxes by changing the .value property. This may sound confusing, but study the below examples for a better understanding.
function my_first_try_ajax(results) {
var targetDiv = document.getElementById('firstDiv');
var resultHTML='<h1>' + results + '</h1>';
targetDiv.innerHTML = resultHTML;
}
The above code replaces the html within a div with the id “firstDiv” with whatever has been returned by myscript.php wrapped in h1 tags. You could have an empty div and only insert html into it on AJAX calls. The div would look like this:
<div id="firstDiv"></div>
While declaring an _ajax hook function is required, adding JavaScript code inside the function is optional. Why? Because often you do not want to change content on the user’s page, but instead just update values in the database on your call to the script specified in the _init hook. In that case, nothing would need to be updated on the page.
Creating your PHP script that will be called by the AJAX framework is easy if you know PHP. You can have your PHP script do pretty much anything. You probably want to either return some value or values, update a database, or both. The only thing to note is that to return a value, you need to “echo” it out. Values printed to the screen from your PHP callback script are returned to the the JavaScript _ajax() hook function as the results variable, as seen above.
How do you return multiple results? Well the implementation differs depending on what you want to return, but if you want to return an array you simply echo out a comma separated list in your PHP script and then you split the returned JavaScript variable by the commas and loop through the values in your _ajax() function and do whatever. Here is an example of a php script that connects to a database and returns the current sales totals for the year:
<?php
//connect to database
$link = mysql_connect('localhost', 'username', 'password')
or die('Could not connect: ' . mysql_error());
mysql_select_db('sales_db') or die('Could not select database');
$currentYear = date('Y');
//execute query
$sql = "SELECT SUM(sale_total) as `total`
FROM sales_table WHERE year = $currentYear";
$result = mysql_query($sql);
//retrieve results
while ($row = mysql_fetch_assoc($result)) {
$total = $row["total"];
}
//return via echo to our JavaScript _ajax function
echo $total;
?>
Here is another example that returns an array of values:
?php
//[not shown] do a database call and retrieve an array
$valueArray = array(23, 231, 'roger 123', 26, 'Las Veags,
Nevada', 'Washington', 77);
//replace commas with their html value so they do not
//get in the way of separating out the array
// values with commas via the implode statement
echo implode(', ', str_replace(',', ',', $valueArray));
?>
Activating AJAX
Finally, the only thing we are missing is how we trigger our AJAX call. There are many ways to do this. The most common method is when a user interacts with an element on the page, triggering the AJAX helper function, but this is not the only way. You can also use a JavaScript timer and call the AJAX at a set interval. This method will be covered in a future article. Let’s look at some common examples of triggering AJAX through user interaction:
Button Click
<input type="button" id="trig" value="ClickMe" onClick="ajaxHelper('my_first_ajax');" >
Mouse-Over a Div
<div id="TriggerDiv" onMouseOver="ajaxHelper('sales_calculate');" ></div>
Click in a Text Box
<input type="text" name="datefield" onClick="ajaxHelper('update_date');" >
The uses for AJAX are endless, especially coupled with PHP. Explore, experiment, and see what’s best for your website.
I added an optional second parameter to the ajaxHelper() function call – this allows you to pass additional variables to the PHP script via Javascript. Below is an example of passing an array of three values to the php script.
Example Usage
<a href="#" onclick="ajaxHelper('track_click', new Array(1303432, 26));">Click Here</a>
To utilize these values, add parameters to your _init hook function for each value passed. The below _init hook function takes each of the passed values and then puts them into a url friendly format to be passed to your PHP script.
function track_click_init(arg0, arg1) {
var script = 'onclick.php';
var queryString = "?id=" + arg0 + "&age=" + arg1;
return script + queryString;
}