Edit: Looking for an easier way to do JSONP in WordPress?
What IS JSONP and why should I care?
There’s been a lot of debate lately about whether to move your site to SLL (https) or not. It’s clear, though, that all your forms, at least the ones that handle sensitive data like logins, should go over a secure connection.
This is where JSONP comes into the picture. As you probably know, you CAN include scripts from other sites using a script tag, that ability is the foundation of CDNs. JSONP takes advantage of that functionality.
Basically, instead of including a static script on your site hosted on a CDN, you’re sending a GET request to the domain of choice, and asking it to send back a callback method including within it a JSON object with the data you want. In essence, you’re spoofing your browser to think that it’s not actually doing a cross-domain ajax call, but in practice, you are.
There’s a great discussion on StackOverflow about JSONP for further exploration.
How do I do it?
Below you’ll find two files, upload them to a folder in your WordPress plugins directory and activate. Note: you should probably run this on a test site. It won’t do anything bad to your site, but it’s never a good idea to play around on your production site.
To test it add the following to any page:
<input name="title" type="text" /> <input name="titleSubmit" type="button" />
The most important pieces in the example that you’ll need to get your code running are:
In the js file:
Clearly without any of the code it won’t work properly; however, the above settings are not typical of most of your standard AJAX calls.
type: GET: By it’s very nature a JSONP call cannot be POST. You’re essentially embedding a script tag on your page with GET variables in the URL of the script.
cache: false: Removing this will not break your code, but for testing it’s best if you your browser doesn’t cache the responses.
dataType: “jsonp”: You’re telling jQuery that it’s a JSONP call. Duh.
crossDomain: true: Perhaps with the dataType set to JSONP you’d think the that this would be enabled, that’s the whole point, but you still need to set this.
In the PHP file:
access-control-allow-origin: *: This is another security check, you need to enable any origin for JSONP to work.
$_GET[‘callback’]: Without the callback wrapping your JSON response jQuery will not recognize this as a valid response. It is set in place as a security measure similar to NONCEs.
Once you have the right recipe, JSONP with WordPress is not all that difficult. Use it well.
As always, questions? comments? Don’t hesitate to do so below.