Writing Your Server-Side Ajax Handler

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:
  1. <?php
  2. function world($params='')
  3. {
  4.   return 'Goodbye Cruel World.';
  5. }//end world
  6.  
  7. function sweetWorldAction($params='')
  8. {
  9.   //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"
  10.   //parse out the variables
  11.   if(!is_array($params))
  12.   {
  13.     parse_str($params,$params);
  14.   }//end if
  15.  
  16.   //do your logic here
  17. }//end sweetWorldAction
  18. ?>

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:
  1. <?php
  2. //if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
  3.  
  4. include('functions.php');
  5.  
  6. //list out your Ajax accessible functions
  7. $valid_functions = array('world','sweetWorldAction');
  8.  
  9. if($_GET['function'] && in_array($_GET['function'],$valid_functions))
  10. {
  11.   //get the get parameters
  12.   $params = $_GET
  13.   //unset the function index from the params because we just don't need it there
  14.   unset($params['function']);
  15.  
  16.   //build your parameter string:
  17.   $param_string='';
  18.   foreach($params as $key=>$param)
  19.   {
  20.     $param_string.=(($param_string)?'&':'').$key.'='.$param;
  21.   }//end foreach
  22.  
  23.   //make your function call
  24.   eval($_GET['function']."('$param_string');");
  25. }//end if
  26.  
  27. ?>

The Variable Variable Method - A Dynamic Handler

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

PHP:
  1. <?php
  2. //if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
  3.  
  4. include('functions.php');
  5.  
  6. //list out your Ajax accessible functions
  7. $valid_functions = array('world','sweetWorldAction');
  8.  
  9. if($_GET['function'] && in_array($_GET['function'],$valid_functions))
  10. {
  11.   //get the get parameters
  12.   $params = $_GET
  13.   //unset the function index from the params because we just don't need it there
  14.   unset($params['function']);
  15.   //make your function call
  16.   $_GET['function']($params);
  17. }//end if
  18.  
  19. ?>

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:
  1. <?php
  2. //if the user leaves the page or closes the browser prematurely, this will help prevent half completed statements
  3.  
  4. include('functions.php');
  5.  
  6. if($_GET['function'])
  7. {
  8.   switch $_GET['function']
  9.   {
  10.     case 'world':
  11.       echo world();
  12.       exit;
  13.     break;
  14.     case 'sweetWorldAction':
  15.       echo sweetWorldAction();
  16.       exit;
  17.     break;
  18.   }//end switch
  19. }//end if
  20.  
  21. ?>

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!

Discuss This Article


19 Responses to “Writing Your Server-Side Ajax Handler”

  1. AvatarZach

    Another reason to use switch over if/else is performance. Switch statements are highly optimized for a lot of conditions.

    Reply to this comment.
    1
  2. Avatarenygma

    grr….it apparently interpreted the PHP from the las one, so here it is again:

    If you didn’t want to use eval (remember, eval’s only one letter away from evil), you can always use variable variables:

    [php]
    function test($parms){
    print_r($parms);
    }

    //be sure to filter the input first!
    $filtered=filterThisInput($_GET);

    $filtered['function_called']($filtered);
    [php]

    calling the page with: page.php?function_called=test&foo=1&bar=2
    would result in:

    Array (
    [function_called] => test
    [foo] => 1
    [bar] => 2
    )

    Reply to this comment.
    2
  3. AvatarMatt
    Author Comment

    @enygma

    Yeah, good point on the eval is one letter away from evil :) Variable variables for the win!

    Reply to this comment.
    3
  4. AvatarJim Plush

    Matt, you should check out the my-BIC php/ajax framework. There is one server file mybic_server.php that pretty much does what you’re looking for, it also supports GET/POST JSON/TEXT/XML request/responses in less than 100 lines of code.
    http://www.litfuel.net/mybic

    Reply to this comment.
    4
  5. Avatarsp

    I think one function for all ajax requests is not a very good idea. First, you have to invent those methods (btw, I always use ’switch’ if I have to create something like that, my non-ajaxed blog-engine for instance), second this makes your script a bit more complicated. However, maybe, it`s just a question of style.

    I prefer another way: for each request I make file, which name consits of ‘xhr’ prefix and the name of the ajax function that ewokes it. So, for the javascript function loadCommentsData with xmlhttprequest inside, I create ‘xhr.loadCommentsData.php’ file to process it.

    Reply to this comment.
    5
  6. Avatarsp

    Damn. Sorry for mistakes and my whole knoledge of english. :)

    Reply to this comment.
    6
  7. AvatarMatt
    Author Comment

    @sp

    I used your suggested method for a while but I found it wasn’t as portable as I’d like it. There is definate power to modularizing the logic into application functions and keeping the Server-Side Ajax handling separate. Handlers do that nicely. They handle the Ajax requests and call the exact same application functions that are used to generate the original page elements on first load.

    It is also important to note that I typically don’t use a single Ajax Handler in my applications. I split them up into appropriate categories. So if I were, say, doing an ecommerce site I may have an account handler, cart handler, and store handler. That is primarily for readability and findability of code ;)

    Now, if you are simply calling application functions within your xhr files, then we are on the same page, it seems. You simply like to split your function calls up a lot more than I do mine :)

    Reply to this comment.
    7
  8. AvatarJared White

    That’s a good start for an Ajax server in PHP. However, as I’ve found, it’s often necessary to have a more advanced response with various commands acting on incoming data, and it’s nice to be able to use PHP to push those commands to the client. My approach is to use something like xajax (which I’m a co-developer of, actually :) ) which lets you register functions or object methods, call them from Javascript with a simple function call, and then you can craft a response using a number of different commands via an easy-to-use response object in PHP.

    Check it out — it’s kind of neat, I think.

    Reply to this comment.
    8
  9. trackback trackback:
    Anonymous

    BorkWeb Writing Your Server-Side Ajax Handler…

    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 …

    Reply to this comment.
    9
  10. AvatarChris

    this maybe a more modular way to call to seperate classes

    $class =$_GET['class'];
    include_once($_SERVER['DOCUMENT_ROOT'].”/classLib/$class.class.php”);
    $obj = new $class();
    $methods = get_class_methods($obj);
    if (in_array($_GET['method'], $methods)) {
    $params = $_GET;
    unset($params['method']);
    unset($params['class']);
    $obj->$_GET['method']($params);
    }else{
    die(’Invalid call!’);
    }

    Reply to this comment.
    10
  11. AvatarNival

    Cool project!

    Reply to this comment.
    11
  12. AvatarJean

    Good site!
    Bye.

    Reply to this comment.
    12
  13. pingback pingback:
    BorkWeb » The Ajax Experience

    [...] MasterWish - a one and a half year old brainchild of a couple of other developers and myself - has been my playground after work hours. I began my experimentation with Ajax using that site, as PSU tended to slap my hand when looking into Ajax at work. Through that experimentation, I began to understand the workings of Ajax and how it would work into the PHP/Templating environment I was so comfortable with. Once I had dug down, I promptly posted my “Ajax; Templating; and the Separation of Layout and Logic” article that Ajaxian blogged about, along with the follow-up article. [...]

    Reply to this comment.
    13
  14. Avatarangelsoft
    14
  15. Avatarhot-asian-babes

    Thanks for your great site!

    Reply to this comment.
    15
  16. AvatarCoble

    I liked this site, it’s neat. Good job! Visit my sites, please:

    Reply to this comment.
    16
  17. AvatarAaronMC

    I was looking at your code.. its a great idea, however I was wondering why you dissected the $_GET variable in your dynamic handler when you could have simply passed the $_GET array to the ajax function (after unsetting the ['function'] key). ie.

    $params = $_GET;
    //unset the function index from the params because we just don’t need it there

    unset($params['function']);
    eval($_GET['function'].”($params);”);

    I was just curious because maybe im missing a good reason that I didn’t see. It just seems that you are doing twice the amount of work.

    Reply to this comment.
    17
  18. AvatarAaronMC

    Sorry, I just realized this is equal to your posted Variable Variable Method!

    Reply to this comment.
    18
  19. AvatarAaronMC

    I also wanted to let you know I am working on a version of this code to get $_POST variables to work as well since HTTP GET has a max header size and will not work for sending larger blobs of data! If anyone has any suggestions please post!

    Reply to this comment.
    19

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Preview:

 (5123) - ajax handler (92) - ajax server (33) - handler (13) - ajax push php (10) - ajax server code (10) - php ajax server (8) - php ajax push (8) - server AJAX (7) - php ajax server push (6) - ajax server side php (6) - php ajax handler (6) - ajax handlers (6) - ajax server side (6) - AJAX SERVER PAGE (5) - AJAX server push (5) - php ajax server side (5) - ajax server-side (5) - xmlhttprequest server side (4) - php push ajax (4) - pass a php variable over to a javascript handler (4) - php server side ajax (4) - writing code in ajax (4) - php ajax request handler (4) - AJAX server side code (4) - ajax handler php (4) - ajax php server (3) - generic handler ajax (3) - setup ajax server (3) - ajax server side script (3) - ajax server php (3) - AJAX POST server (3) - server-side ajax (3) - ajax call to server (3) - ajax server push php (3) - server side push jsp (3) - server side xmlhttprequest (3) - writing a server variable in javascript (3) - server side ajax handler (2) - ajax 1 call multiple response (2) - how to make a call to a server side function dynamically (2) - ajax call server method (2) - how to make a ajax call to handler (2) - writing a server side include (2) - ajax handler function (2) - jsp ajax handler (2) - ajax server side include (2) - accesing server variables with ajax .net (2) - install ajax on server (2) - call server side code from javascript (2) - server side ajax jsp (2) - php server side variable (2) - how to code your server (2) - php request handler (2) - ajax http handler (2) - eval("$_GET[ (2) - call ajax method from server side (2) - php server ajax (2) - httpHandlers AJAX (2) - ajax from server (2) - writing if condition in JavaScript accessing server side variable (2) - server-side XMLHttpRequest (2) - AJAX PHP server push (2) - create server side ajax method for php (2) - ajax post server side (2) - server side php ajax request (2) - write a response to ajax php (2) - ajax calling server side function (2) - ajax php handler (2) - give me one ajax handler example (2) - htaccess (2) - simple php ajax handler (2) - ajax server script (2) - ajax server side scripting (2) - ajax server response (2) - ajax (2) - ajax calling function twice in same page (2) - ajax server side response (2) - ajax-calls handler.php download (2) - asp.net generic handler ajax (2) - prototype server side call (1) - ajax push handler (1) - Calling Http Handler from javascript (1) - ajax writing on the server (1) - call server side method of a class using ajax in javascript (1) - php server push ajax (1) - call server side methods with ajax (1) - writing serverside code in javascript function (1) - how to call server side function using ajax in jsp (1) - write an ajax function (1) - ajax multiple response from server php (1) - setting up your server for ajax (1) - functiom parameter comment (1) - calling server side code with ajax (1) - ajax to run a class from server side (1) - AJAX function with handler as parameter (1) - calling server side code using ajax (1) - server side handlers how to (1) - server side push sample code using jsp (1) - execute server-side code from javascript (1) - how to set up a server for ajax (1) - server side code with ajax (1) - UltraWebMenu not showing up (1) - XHR Push php (1) - server side function caliing in AJAX (1) - how to make AJAX request to a server (1) - Server-Side-Script.PHP (1) - how Create Server-side Handler (1) - tags to execute server side code (1) - ajax jsp server side post (1) - ajax jsp server side using post (1) - setup ajax php server (1) - max post size ajax prototype js (1) - server side php code ajax (1) - ajax server side coding (1) - how to get an array using ajax in jsp (1) - call ajax code on server side (1) - How to use handlers Ajax (1) - how to write php ajax (1) - ajax is a server (1) - woodstock server push (1) - get data from server ajax store in the variable (1) - ajax jsp (1) - writing array ajax (1) - ajax file handler php (1) - run javascript code ajax request eval (1) - how to set server response code for ajax call (1) - ajax server class (1) - codes to make writing to the side (1) - jsp server side code in ajax (1) - .net server-side ajax (1) - ajax server side ajaxmethod (1) - ajax tags Create Server side Handler (1) - xmlhttprequest write to server side file (1) - call to server AJAX jsp (1) - php server side ajax history (1) - write ajax & php code in one file (1) - server setup ajax (1) - AJAX read file server side (1) - writing javascript - AJAX (1) - ajax best server (1) - handle php server response AJAX (1) - writing javascript method in server side code asp.net (1) - ajax Handler is not working on the server (1) - server side handling of AJAX request (1) - handle prototype json server side asp (1) - ajax code along with server side script in jsp (1) - ajax php server-side (1) - Ajax Call Server Methods -static (1) - making ajax call to server (1) -