Created
April 26, 2014 18:40
-
-
Save nickpelton/11327670 to your computer and use it in GitHub Desktop.
WP: AJAX Nounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ = 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); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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