Skip to content

Instantly share code, notes, and snippets.

@karlazz
Last active September 7, 2016 01:03
Show Gist options
  • Select an option

  • Save karlazz/97820f3a17f90f421ca0 to your computer and use it in GitHub Desktop.

Select an option

Save karlazz/97820f3a17f90f421ca0 to your computer and use it in GitHub Desktop.
WP_ajax basics with nonce security part not tested
// this goes in the page template or where you need it
// make sure that your add_action and your callback are in functions, not in a page template
wp_enqueue_script('karla');
$ajax_nonce = wp_create_nonce( "karla-nonce" );
wp_localize_script('karla','getter',array('ajax_url' => admin_url( 'admin-ajax.php' ),'sugar'=>$_GET['sugar']), 'security'=> $ajax_nonce );
——————
//functions.php
add_action('wp_enqueue_scripts','addmyscript');
function addmyscript() {
wp_register_script(
'karla',
get_stylesheet_directory_uri() . '/karla.js',
false,
'1.0',
true
);
}
add_action( 'wp_ajax_karla_ajax', 'karla_kallback' );
add_action( 'wp_ajax_nopriv_karla_ajax', 'karla_kallback' );
function karla_kallback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
check_ajax_referer( 'karla-nonce', 'security' );
echo $whatever;
die();
}
//here is the javascript that goes in karla.js
jQuery(document).ready(function($) {
alert (getter.sugar); /* this comes via wp_localize_script and $_GET */
var data = {
'action': 'karla_ajax',
'security': getter.security,
'whatever': 505
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(getter.ajax_url, data, function(response) { /* the ajax_url has to be set in wp_localize */
alert('Got this from the server: ' + response);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment