Instantly share code, notes, and snippets.

Embed
What would you like to do?
wp_jsonp
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);
}
});
};
<?php
/**
* Plugin Name: WordPress JSONp Helper
* Plugin URI: http://www.jackreichert.com/2015/07/02/how-to-jsonp-ajax-to-ssl-in-wordpress-an-easier-way/
* Description: A paradigm for easy AJAX over SSL in WordPress using JSONP.
* Version: 0.1
* Author: jackreichert
* Author URI: http://www.jackreichert.com/
* License: GPL3
*/
class WP_AJAX_JSONp {
// actions on instatiation
function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'wp_jsonp_scripts' ) );
}
// enqueue scripts
function wp_jsonp_scripts() {
wp_enqueue_script( 'wp_jsonp_script', plugins_url( '/jsonp.js', __FILE__ ), array( 'jquery' ) );
wp_localize_script( 'wp_jsonp_script', 'wp_jsonp_vars', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'wpAJAXNonce' => wp_create_nonce( 'wpAJAX-nonce' )
) );
}
}
$WP_AJAX_JSONp = new WP_AJAX_JSONp();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment