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
Client Launch: Bring Light
Client Launch: Bring Light

Congratulations to Bring Light! They recently launched and we want to thank Drew of Bring Light, Ruby ...

Next
High Concept Revisted: Aligning Vision with Effort
High Concept Revisted: Aligning Vision with Effort

In an earlier post, I discussed high concept and how it can focus an entrepeneur. High concepts ca...

Enter curious. Exit smarter.

Register Now