Using JSON on the request with Ajax.Request postBody

May 16, 2007 Pivotal Labs

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)

About the Author

Biography

More Content by Pivotal Labs
Previous
Redefining Constants
Redefining Constants

We all like a good oxymoron, like redefining constants. There are times where we need to redefine a constan...

Next
Best Remote Pairing Audio/Video Options
Best Remote Pairing Audio/Video Options

Dave asked about this, in response to my "Best Remote Pairing Settings" post (http://www.pivotalblabs.com/a...

×

Subscribe to our Weekly Newsletter

!
Thank you!
Error - something went wrong!