Posted on April 9, 2008 in AJAX, Javascript, PHP by Elliott BrueggemanNo Comments »

Background

Previously I posted my PHP AJAX Framework so I thought I would give an example of its use. In this case, you probably have seen this example before - using AJAX and PHP to check if a username is available during some kind of web-based user registration. The goal is to alert the user if a username is taken before they have submitted the form, allowing them to enter another username quickly. This feat can be easily accomplished with the PHP AJAX Framework.

Setup

You are going to need to copy the contents of the PHP AJAX Framework into a JavaScript file. In this example I have put the contents into the “php_ajax_framework.js” file. You are also going to need to write a PHP script that will be called in the AJAX sequence of events, notifying the user whether the username is available or not.

Below is an example PHP Script, which has the filename “username_exists.php” and will need to be in the same directory as the page that is triggering the AJAX.

PHP Username Available Script

This script is requested by our AJAX helper function and sent the text in our username input box. In the script is a call to a function usernameExists() which returns true or false, depending on whether the username exists. In a real web site or application, this would query our database to see if the username existed. In this example, for ease of understanding, we just check to see if the username is in a defined array of usernames.

<?php 
$username = trim($_GET['username']);
 
if (usernameExists($username)) {
  echo '<span style="color:red";>Username Taken</span>';
}
else {
  echo '<span style="color:green;">Username Available</span>';
}
 
function usernameExists($input) {
  // in production use we would look up the username in 
  // our database, but for this example, we'll just check
  // to see if its in an array of preset usernames.
  $name_array =  array ('steve', 'jon', 'george', 'admin');
 
  if (in_array($input, $name_array)) {
    return true;
  }
  else {
    return false;
  }
}
?>

Username Check Page

Our example username page is very basic - you should integrate this into your existing site. The important parts are the JavaScript functions and the input box, which uses the onKeyUp() JavaScript event to call a function which them triggers the AJAX chain of events. More information on setting up the PHP AJAX Framework can be found on its post page, but the basic idea is that you create an _init function that specifies which PHP script to execute and what variables to send it (in this case, the value of the user input box.) You also create a _results function which will be given the results of your PHP Script and then do something with them (in this case, display a notice to the user whether the name is available.) The _init and _results functions are given function names prepended to these terms which are the same (in the below case, we prepend “check_username” to both) and then they are triggered by calling our PHP AJAX Framework function ajaxHelper() with the name we prepended.

<html>
<head>
<script type="text/javascript" src="php_ajax_framework.js"></script>
<script type="text/javascript">
function check_username_init() {
  var user_field = document.getElementById('user');
  return 'username_exists.php?username=' + user_field.value;
}
function check_username_ajax(results) {
  var results_div = document.getElementById('results_div');
  results_div.innerHTML = results;
}
function check_username() {
  var user_field = document.getElementById('user');
  if (user_field.value.length > 0) {
    //call our AJAX function in the PHP AJAX Framework
    ajaxHelper('check_username');
  }
  else {
    //clear results field 
    var results_div = document.getElementById('results_div');
    results_div.innerHTML = '';
  }
}
</script>
</head>
<body>
Username: 
<input name="user" id="user" size="20" onKeyUp="check_username();">
<div id="results_div"></div>
</body>
</html>

Here is an live example of the above scripts all working together. Remember that we are just checking against an array of names. Try typing in one of the names in the array to see what happens when a particular username is taken (steve, jon, george, admin.)

Conclusion

Implementing AJAX is easy and just requires putting all the pieces together. Give AJAX and shot and implement the PHP AJAX Framework on your site for simple AJAX tasks.

Posted on January 16, 2008 in AJAX, Javascript, PHP by Elliott BrueggemanNo Comments »

Background

In the previous article, we examined the PHP AJAX Framework, which is an easy way of combining AJAX with PHP. In order to trigger our AJAX, we relied on user interaction. However, what happens when you want your AJAX call to execute at a certain time interval? The solution is relatively easy and involves the JavaScript function setInterval().

AJAX Timer Code

Below is a snippet of JavaScript code that will work with my PHP AJAX Framework to call the sales_calculate hook every 5 seconds:

<script language="JavaScript">
var time = 5; //time in seconds
var interval = time * 1000;
var timer = setInterval("ajaxHelper('sales_calculate')", interval);
</script>

The above code will execute our ajaxHelper() function with the sales_calculate hook that will in turn call sales_calculate_setup() and then sales_calculate_ajax() every 5 seconds.

Note that this code is meant to accompany my PHP Framework, and will not trigger an AJAX call unless properly configured. Please refer to the prior AJAX Framework article for more information.

Posted on January 9, 2008 in AJAX, Javascript, PHP by Elliott Brueggeman1 Comment »

Background

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.

AJAX Workflow

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.

  1. Using JavaScript, a call to your AJAX function is triggered by clicking somewhere, entering something, etc.
  2. Your AJAX function creates an XMLHttpRequest object.
  3. When ready, the object requests information from your server in the form of a URL, possibly with arguments such as myscript.php?name=jon&year=2007, etc.
  4. The server executes the PHP script and sends the result by echo[ing] it out.
  5. Instead of printing it to the screen, that information is instead returned to you as a JavaScript variable.
  6. Using JavaScript, that information can now be dynamically inserted in the page by using the innerHTML property or by assigning the result to the value of a form element.
  7. Rinse and Repeat… The value of AJAX is that you can repeat this process infinitely without having the user have to navigate away from the page!

PHP AJAX Framework

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) {
  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
  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.

Your PHP Script

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(',', '&#44;', $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');" >

Conclusion

The uses for AJAX are endless, especially coupled with PHP. Explore, experiment, and see what’s best for your website.