Skip to content

Instantly share code, notes, and snippets.

@nickpelton
Created April 26, 2014 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickpelton/11327670 to your computer and use it in GitHub Desktop.
Save nickpelton/11327670 to your computer and use it in GitHub Desktop.
WP: AJAX Nounce
<?php
/**
* Setup JSON Ajax endpoint
*/
add_action('wp_ajax_secure_endpoint', 'secure_endpoint_callback_function');
add_action('wp_ajax_nopriv_secure_endpoint', 'secure_endpoint_callback_function');
function secure_endpoint_callback_function(){
// Nonce Security check
check_ajax_referer( 'my-secret-string', 'security' );
echo "You have access!";
die();
}
$ = jQuery.noConflict();
jQuery(document).ready(function(){
// Access WP data using $.ajax()
$.ajax({
method: "POST",
dataType: "HTML",
url: myLocalizedData.ajax_url,
data: {action:'secure_endpoint',security: myLocalizedData.ajax_nonce},
}).done(function(myAjaxData){
// Place Data in DOM
$('#displayData').append(myAjaxData);
});
});
<?php
// enque script
wp_enqueue_script( "myScript", site_url()."/assets/s9/myscript.js", array('jquery'), '1.0',true);
// Setup our data
$myDataArray = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'my-secret-string' )
);
// Pass data to myscript.js on page load
wp_localize_script( "myScript", "myLocalizedData", $myDataArray );
// wp_localize_script( $handle, $objectName, $arrayOfValues );
// $handle - The enqueued script to place the data immedietly before
// $objectName - Name of the JS object that will hold the data
// $arrayOfValues - Data to pass to JS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment