Writing Your Server-Side Ajax Handler

[[innerindex]]In my recent post on ‘Ajax; Templating; and the Separation of Layout and Logic,’ I refer to an Ajax Handler that sits server side to handle Ajax calls. Some elaboration is in order.

As I have stated in the past, I’m a huge fan of Prototype AND I choose PHP as my language of choice…so my examples will be using both, but the idea is portable.

Set up your Functions

Before you create a handler, you need a set of functions that the handler can reference. Here’s an example:

< ?php
function world($params='')
{
  return 'Goodbye Cruel World.';
}//end world

function sweetWorldAction($params='')
{
  //we expect params to be an array or a string similar to a parameter string from a GET..i.e. "bork=asdf&cheese=yes please"
  //parse out the variables
  if(!is_array($params))
  {
    parse_str($params,$params);
  }//end if

  //do your logic here
}//end sweetWorldAction
?>

Now that we have the functions all set, we’ll set up a handler that receives Ajax calls and calls the appropriate functions.

The Eval Method – A Dynamic Handler

This method is one that I toyed around with for a while and I’ll admit that its pretty simple and clean but there are some drawbacks. We’re going to make a few assumptions: All requests will be GET (this is to keep things simple for this example) and we will keep the complexity of .htaccess sweetness out of these examples and assume that each call will be passing a function variable that specifies the function we are calling. I’ll get to those in a second…but first I’ll show you the handler code in this Eval Method:

< ?php
//if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
ignore_user_abort();

include('functions.php');

//list out your Ajax accessible functions
$valid_functions = array('world','sweetWorldAction');

if($_GET['function'] && in_array($_GET['function'],$valid_functions))
{
  //get the get parameters
  $params = $_GET;  
  //unset the function index from the params because we just don't need it there
  unset($params['function']);

  //build your parameter string:
  $param_string='';
  foreach($params as $key=>$param)
  {
    $param_string.=(($param_string)?'&':'').$key.'='.$param;
  }//end foreach

  //make your function call
  eval($_GET['function']."('$param_string');");
}//end if

?>

The Variable Variable Method – A Dynamic Handler

This method (compliments of PHPDeveloper) is simpler than the Eval Method and just as dynamic.

< ?php
//if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
ignore_user_abort();

include('functions.php');

//list out your Ajax accessible functions
$valid_functions = array('world','sweetWorldAction');

if($_GET['function'] && in_array($_GET['function'],$valid_functions))
{
  //get the get parameters
  $params = $_GET;  
  //unset the function index from the params because we just don't need it there
  unset($params['function']);
  //make your function call
  $_GET['function']($params);
}//end if

?>

The Switch Method – A Basic Handler

This method handles each call individually. The reason for using switch rather than if-elses is simply because your application will most likely possess a large number of Ajax-ified functions and those if-elses would be ghastly to read and decrease performance…the Switch statement is much cleaner.

< ?php
//if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
ignore_user_abort();

include('functions.php');

if($_GET['function'])
{
  switch $_GET['function']
  {
    case 'world':
      echo world();
      exit;
    break;
    case 'sweetWorldAction':
      echo sweetWorldAction();
      exit;
    break;
  }//end switch
}//end if

?>

Make a Choice

Which are you going to use? While the Eval and Variable Variable Methods contain very small amounts of code in the handlers, the logic has simply been shifted to the functions themselves. Increased Ajax-geared logic within the functions themselves reduces portability. However, in the Switch Method, logic is organized in a fairly easy to follow manner while making use of very generic functions that can be used in multiple fashions. Obviously, the Switch Method is my preferred choice :)

In Closing

Handler scripts make the Ajax magic happen and the separation of handler logic from your application logic is just as important for robust development and debugging as the need for separation of layout and logic. Play around with the above methods and see which works for you. If you have a method all your own, I’d be interested to hear it!