I’ve been (essentially) the lead (only) developer for our company’s widget over the last couple months. And while that is actually pretty scary, I now know way more about JQuery, Javascript and AJAX than I did before. One thing that stumped me for a bit this week was JSONP.

JSONP is ‘JSON with Padding’ which was originally proposed in this blog post. The most important part from an environmental and testing perspective is but requires a little bit of server-side cooperation.

From a testing perspective, you should check that the app behaves in a predictable manner if the server side call doesn’t work, or the format of the response is not correct (I cannot explain how much I am sick of seeing ‘invalid label’ show up in FireBug).

And from an environmental setup perspective, you need to get your servers dishing out the correct messages. Here is a perl script which will respond correctly to JQuery’s getJSON method when ?callback=? is appended to the request url.

#!/usr/bin/perl

# UPDATE THIS SECTION
$raw_json = "
{
  'offsets': [
    {
      'name': 'Methane Offset',
      'unit': 'ton',
      'currency': 'USD',
      'cost_per_unit': 14,
      'source': 'http://www.thisoffsetssource.com'
    }
  ]
}";

# DO NOT CHANGE ANYTHING BELOW

use CGI qw(:standard);
use JSON;

$enable = true;

$json = new JSON;
$json = $json->allow_nonref([$enable]);

$raw_json =~ s/\n//g;
$json_text = $json->encode($raw_json);

print "Content-type: application/json\n\n";
$callback = param('callback');
if (length($callback) > 0) {
   print $callback . "(" . $json_text . ")";
}

It should be generic enough that all you need to do to use this in your environment is replace the JSON stored in $raw_json and the rest should just work.

Resources: