Using AJAX in WordPress
Written on December 20, 2014
Most of the work of setting up an ajax action in the WordPress environment happens in php-land.
The PHP File
Register & enqueue your script. In this example, I’ll assume the script has already been registered.
wp_enqueue_script( 'myscript' );
*I’ve had trouble when I’ve tried to enqueue the script at the wp_enqueue_scripts action and added the part below in the wp_head action (the wp_localize_script() function should be run during the wp_head action.). Enqueueing the script at the wp_head action (in the same the closure function below) seemed to work fine.
Localize the script. Also check for whether https or http is being used to avoid cross-browser origin issues.
add_action('wp_head',function() { if( ! empty($_SERVER['HTTPS']) ) $args = array('ajaxurl' => admin_url( 'admin-ajax.php','https' ) ); else $args = array('ajaxurl' => admin_url( 'admin-ajax.php','http' ) ); wp_localize_script( 'myscript', 'myajaxsettings', $args ); }
Write the php function that will be executed when doing the AJAX call.
function myServerFunction() { echo 'Hi there.'; }
Next we need a handle for your ajax action which will allow WordPress to connect the server function with the client call. In this case, let’s use the string our_ajax_action. Note that you should not use hyphens in this handle. WordPress will prepend your string with one of two prefixes, depending on whether the viewer is logged in or not. So to create the ajax connection for logged in users, use wp_ajax_, like wp_ajax_our_ajax_action. To create the ajax connection for viewers who are not logged in, use wp_ajax_nopriv_, like wp_ajax_nopriv_our_ajax_action. Note: If you want your ajax call to happen regardless of whether someone is logged in, you have to explicity use both.
Now create the connection between the handle you just created and the function you just created. For this example, we’ll do our ajax for both logged in and non-logged-in viewers.
add_action('wp_ajax_our_ajax_action','myServerFunction'); add_action('wp_ajax_nopriv_our_ajax_action','myServerFunction');
The Javascript File
Finally set up your javascript to execute the ajax and handle the response from your myServerFunction() function. Note that myajaxsettings and ajaxurl needs to match what you used in the wp_localize_script() function above. our_ajax_action should match the string you used as a handle above, without the wp_ajax_ or wp_ajax_nopriv_ prefixes.
$.post( myajaxsettings.ajaxurl , { action: 'our_ajax_action' }, function(response) { // this is where you do something with 'response', which will be holding // whatever yourmyServerFunction() echoed out. });