Home > JavaScript, PHP, ajax, work > Undocumented JSON support in Prototype

Undocumented JSON support in Prototype

I’m working on a project that’s requiring me to learn a little AJAX. I decided early on to use the Prototype JavaScript framework. It adds a number of things that really should be in JavaScript to begin with, and a few others that it could really use (another post?). It also speeds the process of AJAX development. In the process, I discovered the Prototype also handles most of the JSON lifting for you, if you decide to send the data in JSON format rather than XML. The Prototype documentation doesn’t mention the JSON support, so I had to do a little research. Read the comments in the code:

The PHP Part

The php script that generates the response uses php-json extension to quickly and easily pass a JSON object with the header:

//a whole bunch of code and then:
$response_object->response_text = "My, you’re handsome.";
//create the JSON object & add parentheses where prototype is going to need them (bug in Prototype)
$json_output =(.json_encode($response_object).)‘;
//send the JSON object in the response header - that?~@~Ys the way Prototype likes it
header("X-JSON: $json_output"); 

And The Javascript:

Assume there are divs named ‘response message’ and ‘error’, which are being populated with the innerHTML calls:

//trivial function to ease creating an AJAX request
function ajax_request(url, data) {
    var myAjax = new Ajax.Request(
    url,
    {method: 'get', parameters: data, onComplete: ajax_response, onFailure: reportError});
}

//put the value of the response property from the json object
//notice the json parameter - that’s passed MAGICALLY from outer space, already interpreted
function ajax_response(originalRequest, json) {
    $('response_message').innerHTML = 'The JSON response is ' + json.response_text;
}

function reportError(request) {
    $('error').innerHTML = 'AJAX Error';
}

//create the AJAX request
ajax_request('ajax_server_monitor.php', 'command=mysql_status');

I got some help from Lindsey Simon at FineTooth. The key information left out in her article was that the evaluated json object is passed along to the OnSuccess or OnComplete function as the second parameter. That’s what got me digging into the Prototype source and ultimately blogging this.

social bookmark of choice:
  • Digg
  • del.icio.us
  • Ma.gnolia
  • Reddit
  • Slashdot

Greg JavaScript, PHP, ajax, work

  1. No comments yet.