Page 3

The Server

We last saw how to make bundled AJAX requests, so now let’s take a look at how to unbundle those requests on the server, but before we do that we need to know what format the data is sent to the server in the first place! Once we know the data’s format, we can process it, and send back our response. And with that strategy, let’s dive into the code:

[code lang=’php’ line=’35’]
// get the JSON input and parse
$json_in = “”;
     $json_in = stripslashes($_REQUEST[“data”]);
     $json_in = $_REQUEST[“data”];
$data = json_decode($json_in);
(Yes, magic quotes are of the devil).

Looks simple enough – all of the data comes into the server through a single parameter: data. This parameter is encoded JSON, so all we need to do is decode it, and we have the exact JSON data that was sent into each .bAjax() call on the client-side.

Processing the Request

Now that we have our data, let’s take a look at how we process it:

[code lang=’php’ line=’45’]
// prep the response
$ret = array();

// track how many “up” and “down”
// that the user sent in, if any
// (it could just be a “refresh”
//  command)
$the_number = getCount();
$delta = 0;
          if($data[$i]->func == “down”) $delta -= 1;
          else if($data[$i]->func == “up”) $delta += 1;
          $ret[] = $the_number + $delta;

The input data is simply an array of JSON objects. Each object represents a single AJAX request, so all we need to do is simply loop over the input data to process each request – easy!

As we process each item, we store the results for that request in the $ret array, which we’ll send back later as our response. In our case, this response is simply an array of integers, each integer representing the value of The Number after that exact request was processed. An entire JSON object could just as easily be sent back as the response for each item.

[code lang=’php’ line=’74’]
// send the result back
echo json_encode($ret);

All in all, unbundling the data on the server is extremely straight forward. Just loop over the single JSON input parameter, and then process the request as normal! Now you have all the information you need to start implementing bundled AJAX in your application – but for those of you who want to know even more, let’s take a look at exactly how the bundled AJAX library works:

Leave a Reply

Your email address will not be published. Required fields are marked *