jQuery AJAX Messaging

Jobs from Indeed

When creating AJAX driven web sites (a.k.a a Web 2.0 site) it can be beneficial to develop a common messaging scheme to use for your AJAX requests and responses.

The idea is to use a common PHP script on the web server to handle the requests and send responses, use jQuery to form the requests in the browser and process the response, and use JSON objects and POST parameters to contain the data as it is transported.

   Web Server             Internet                        Web Browser
PHP Handler < -----  [JSON] ----- > jQuery Command Processor

PHP Handler

Since the PHP handler will process all requests it is necessary to specify a required parameter to be provided with every request from the web browser that will tell the handler what action is expected of the PHP handler. As an example we could require that all requests include the parameter 'command' as a POST variable to tell the handler which command should be executed.

Once the handler knows what command it is supposed to execute it is only a matter of processing any additional parameters supplied with the request and respond with a JSON object.

In this example there is a single 'hello' command that returns a hello string 'Hello world!'. If a command is not provided or there is no match then an error message is returned.

$errors = array();
$json = array();
if (isset($_POST['command'])) {
  switch ($_POST['command']) {
    case 'hello':
      $json['hello'] = 'Hello world!';

      $errors[] = 'Unknown command!';
else $errors[] = 'Command required!';

// make sure json is not cached
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

$json['errors'] = $errors;
echo json_encode($json);

jQuery Command Processor

When creating cross browser compatible Javascript code it is helpful to utilize libraries like jQuery that handle many compatibility issues transparently. Below we have a Javascript function that utilizes the jQuery post method to send a command to the previous PHP handler. The command accepts an object that defines the command to execute, any additional parameters and an optional callback function to process the results.

// post command to web server handler and return the result s to callback if provided
function PostCommand(cmd) {
  * cmd must be an object with a settings element containing another
  * object with the command parameter and any additional parameters to
  * be POSTed to the handler with the command.
  * The cmd object may also contain an optional callback function to process results.
  * I.E.
  * cmd = {settings: {command: 'updateItem', item: 'box', quantity: 10}};

  $.post('handlerJSON.php', cmd.settings, function(rsp) {
    // convert response to a JSON object
    if (rsp) rsp = eval( '(' + rsp + ')' );

    // notify of any errors
    if (rsp.errors && rsp.errors.length > 0) {
      msg = '';
      if (typeof(rsp.errors) == 'object') {
        for (i = 0; i < rsp.errors.length; i++) msg += rsp.errors[i] + "\n";
      else msg = rsp.errors;


    // if we have a callback then return the results
    if (cmd.callback) {
      if (rsp) cmd.callback.call(this, rsp);
      else cmd.callback.call(this, false);

The following is an example call to our jQuery command processing function that will call the hello command and then display the results.

  settings: {
    command: 'hello'
  callback: function(data) {
    // if no errors were returned and we have a hello result then display it
    if (data && data.errors.length == 0 && data.hello) {


The preceding code demonstrates a basic method of AJAX messaging using a PHP script as the back end message handler on the server and a Javascript function that relies on the jQuery post method on the front end to send messages and receive responses.

A demo or this code can be viewed here.

And you can download the source files for the demo here.

Sidebar Item