This is a basic example of how to use AJAX in WordPress in the admin area. It shows how to take a variable from javascript, pass it to a PHP function (altering it slightly), and then pass it back to the javascript.
This assumes you already know how to enqueue javascript, etc.
Javascript Piece
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: example_ajax_obj.ajaxurl,
data: {
'action': 'example_ajax_request',
'fruit' : fruit,
'nonce' : example_ajax_obj.nonce
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
PHP Piece
<?php
function example_ajax_request() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'example-nonce' ) ) {
die( 'Nonce value cannot be verified.' );
}
// The $_REQUEST contains all the data sent via ajax
if ( isset( $_REQUEST ) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r( $_REQUEST );
}
Using with a Theme
There’s two differences when using this with a theme or frontend.
PHP Update
In the PHP piece, you need to add also add this line:
// Always die in functions echoing ajax content
die();
This allows visitors that aren’t logged in to run the ajax request.
Javascript Update
In the javascript piece on the frontend, you’ll likely see this error in the console:
wordpress ajaxurl is not defined
This is because WordPress does not define ajaxurl as a global variable on the frontend. Instead, we’ll need to define it ourselves. An easy way to do this if we’re already enqueuing our script is to use wp_localize_script to output the URL:
<?php
function example_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_enqueue_script(
'example-ajax-script',
get_template_directory_uri() . '/js/simple-ajax-example.js',
array( 'jquery' )
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'example-ajax-script',
'example_ajax_obj',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'example-nonce' )
)
);
}
add_action( 'wp_enqueue_scripts', 'example_ajax_enqueue' );
If you view the source on the frontend, you should now see a global variable defined on the frontend called “example_ajax_obj”. To get the original javascript working on the frontend, update the ajaxurl variable to use this new variable:
url: example_ajax_obj.ajaxurl