Steve ConoverSteve Conover
Using JSON on the request with Ajax.Request postBody
edit Posted by Steve Conover on Wednesday May 16, 2007 at 03:52PM

This is nice in a heavy Ajax application - you can use the same data format on the request and the response.

You might not have been aware that prototype'sprototype's Ajax.Request can send a postBody, instead of parameters.

So if you don't mind all of your Ajax requests being POSTs (I don't), you can just ignore serializing parameters and just stick JSON in the postBody.

This makes my jsunit tests (and therefore my production code) nicer:

BEFORE:

<code>
function testRequest() {
  var settings = {volume:"high", color:"red"}

  var command = new SaveSettings(settings);

  assertEquals("/save_settings", command.asAjaxPayload().url);
  assertEquals("volume=high&color=red", command.asAjaxPayload().parameters);
}
</code>

AFTER:

<code>
function testRequest() {
  var settings = {volume:"high", color:"red"}

  var command = new SaveSettings(settings);

  assertEquals("/save_settings", command.asAjaxPayload().url);
  assertEquals(settings, JSON.parse(command.asAjaxPayload().postBody));
}
</code>

(and of course, you can push the stringifying of the post body down a layer, to get rid of the JSON.parse at this level)