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!

Ajax, More Than A Buzz Word

Ajax the development technique, not to be confused with Ajax the cleaning solution, is taking the web by storm. What is it?

Ajax stands for Asynchronous Javascript And XML. Its an architectural methodology on the interactions between a number of different technologies in a way that provides a more seamless user experience between user-to-server communication.

There are tons of blogs and articles out there that rant and rave of its use as savvy site designers implement Ajax into their web applications, and rightly so. However, through my blog skipping and digg watching I have seen numerous complaints of “OMG, Ajax is stupid….its just a fad/buzzword/etc” or “Ajax is just overhyped, don’t know why people use it!!” I have a couple words that describe those people: cynical, ignorant and, well…squirrel handed. Wake up people. Ajax isn’t a fad, its an architectural change in the way that web applications function. A focus on application speed and uninterrupted user interaction.

What’s so great about it? Why do I pee my pants with glee every time I use a web app that makes use of the technology?

I’m a developer. I’ve been developing database driven web applications for a number of years now and have seen the clear line between a desktop application and a web application. Desktop applications are highly interactive and responsive to the user, where web apps (in the past), were fairly static locations (however dynamic the content) to provide information/entertainment to the user, where user interaction required page loads in order to store information to a database/write to a file.

Next came Flash, an excellent tool but tends to require a much more artistic flare and is much more time consuming with general maintenance than its worth.

The reason Ajax is so sexy is that it bridges the gap.

The average-Joe browser may not be aware when they stumble upon a site that makes good use of Ajax, but that average Joe can feel something right about it. To the avid browser, however, an Ajax site is more readily obvious; you can interact with elements on a page and save settings without reloading; pages are highly resposive to user input with minimal wait times.

Gmail and Google Maps were the applications that really brought Ajax into the limelight. (They weren’t the first, just the first major apps). The world saw what Google could do and followed suit. The world saw that it was good. The Ajax revolution was born. It has birthed a whole new breed and boom on the internet, bringing forward a multitude Ajax enabled sites and applications:

And thats just the tip of the iceberg. I look forward to what will become of our expectations of web applications. You won’t see me sitting idle during this evolution. I will be innovating and participating all along the way.