Making an AJAX call to a custom WordPress plugin script

Today we are going to learn about making an AJAX call to a custom WordPress plugin. This method will allow you to make a call to your plugin using JavaScript. The call will be processed by a custom PHP function and a response returned.

To make AJAX calls to a custom plugin script, that has access to WordPress objects and functions, two hooks must be used; wp_ajax_$action and wp_ajax_nopriv_$action; where $action refers to an AJAX requests action property.

Each AJAX request must be made to the admin-ajax.php script. To get the URL for the admin-ajax.php script, the admin_url() function can be used, as shown below.

$ajax_url = admin_url( 'admin-ajax.php' );

The plugin function that will process the AJAX request must be hooked to both of the wp_ajax actions above. custom_action_name should match the AJAX requests action property and custom_function_name is the name of the plugin function that will process the AJAX request, as shown below.

add_action( 'wp_ajax_custom_action_name', 'custom_function_name' );
add_action( 'wp_ajax_nopriv_custom_action_name', 'custom_function_name' );

function custom_function_name() {
  // code to process AJAX request
}

In order to make the URL to the admin-ajax.php script available in your JavaScript file you can use the wp_localize_script function after registering, but before enqueueing a script, as shown below.

wp_register_script( 'ajax-script', plugin_dir_url(__FILE__) . 'js/ajax-script-name.js' );
$wp_vars = array(
  'ajax_url' => admin_url( 'admin-ajax.php' ) ,
);
wp_localize_script( 'ajax-script', 'wp_vars', $wp_vars );
wp_enqueue_script( 'ajax-script' );

The admin-ajax.php URL can now be accessed inside your JavaScript file as a property of the wp_vars object, as shown below.

var ajax_url = wp_vars.ajax_url;

Now all that’s left to do is to make the AJAX request. For brevity I will not go into the complexities of creating a cross-browser AJAX request. The code below should work in most modern browsers.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if( xhr.readyState === 4 && xhr.status === 200 ) {
    console.log( xhr.responseText );
  }
}
var ajax_url = wp_vars.ajax_url;
xhr.open( 'POST', ajax_url, true );
xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
var params = 'action=custom_action_name';
xhr.send( params );

By using a few built-in WordPress functions, making an AJAX call to a custom WordPress plugin script is made possible.

References