How to use JSONP (AJAX to SSL) in WordPress, an EASIER way

I’ve already written about How to use JSONP in WordPress Development. I explain how it works, and why you would use it there.

At work we work with several domains and I’ve had to use quite a bit of JSONP, I’ve rethought how to use it, and made this micro-framework to make it a LOT easier. Mostly, I wrote this to solve the problem that I’m using a lot of AJAX, and don’t want the overhead of the .ajax call each time.

There are a lot of values you need to set when making a JSONP call in general, and specifically with WordPress, this greases those wheels.

The paradigm is all you do is execute:

wp_jsonp("wp_jsonp", "getStuff", {variable: "hello world"}, getStuff);

and the rest is taken care of on the JS side. I wrote it to be agnostic of the server-side processing as well, this gives you the benefit of a pseudo factory design pattern with your switch statement.

You can download the whole repo to peruse or play with if you like, I made some gists for easy embedding.

This is the guts of the operation, I created this javascript object that handles everything, you past the ajax event, method, parameters and a callback function. The plugin takes care of the nitty gritty details that are a pain to remember for getting jsonp to work.

It’s well commented, so read through and feel free to ask questions in the comments if you have any.

if (typeof wp_jsonp === 'undefined') var wp_jsonp = function (event, method, params, callbackFunc) { // data needed to send jsonp var data = { action: event, // wp ajax action ajaxSSLNonce: wp_jsonp_vars.wpAJAXNonce, // nonce method: method, // server has switch/case for processing params: params // data to be processed };

jQuery.ajax({ type: "GET", // this is the essence of jsonp url: wp_jsonp_vars.ajaxurl, // wp ajax url cache: false, // to ensure proper data response dataType: "jsonp", // jsonp crossDomain: true, // enable ssl/nonssl data: data, // data to be sent

success: function (response) { //console.log('success', response); // your callback function callbackFunc(response); },

complete: function (response) { //console.log('complete', response); },

error: function (response) { console.log('error', response); } }); };

admin\_url( 'admin-ajax.php' ), 'wpAJAXNonce' => wp\_create\_nonce( 'wpAJAX-nonce' ) ) ); } } $WP\_AJAX\_JSONp = new WP\_AJAX\_JSONp(); Here’s the example, you might say, wait a minute, don’t you get a callback from jQuery already? Sure, good luck using it. It’s a little funny ignoring that, but hey, this works nicely.

Tags: AJAX, javascript, jsonp, Plugins, WordPress