A modern way of AJAX in WordPress using REST API

Estimated reading time: 6 minutes

A quick Google search reveals that the most common way of calling AJAX in WordPress still uses

admin-ajax.php
admin-ajax.php. In this post, we show you the modern way of using AJAX in WordPress using the REST API. This way is applicable for WordPress versions 4.7 and above. 

Pre WordPress 4.7, REST API is available with the help of a plugin. However, this dependency is not desirable. In later versions of WordPress, REST API Content Endpoints are now part of the WP core. 

What Is AJAX?

AJAX stands for Asynchronous Javascript and XML but very few use XML today and more JSON. However, it is still referred to as AJAX

.An HTTP request originates when an event occurs. These events can be mouse clicks, hovers, etc. This request passes over the Internet to the server where it processes it and sends a response back to the originating browser. The browser processes the data that it receives and updates the page with new content.

The old way of using AJAX

Let’s first look at the old way using

admin-ajax.php
admin-ajax.php . This is simply for reference and should not be used. 

Enqueuing and localizing script(s)

Mostly this code is present in

functions.php
functions.php file.

The above code is very common. I have enqueued the JavaScript file using the wp_enqueue_script function. Now focus on the wp_localize_script function. This function accepts an associative array and creates a Javascript Object which can be used anywhere at the client-side. 

In other words, I have used the wp_localize_script function to create a javascript object and the object is used in the path-to-js-file.js file mentioned in line 6.

For example, I can use it like

myObj.ajaxurl
myObj.ajaxurl or
myObj.nonce
myObj.nonce

In line 9 the

function admin_url(‘admin-ajax.php)
function admin_url(‘admin-ajax.php’) dynamically generates the ‘ajaxurl’ and returns the full path to the PHP file for AJAX. 

In line 10 the wp_create_nonce (‘my-nonce’) function dynamically generates a serial key or token nonce which we will use for our AJAX request.

Using a jQuery call

Note that this is still the old way to do this. Focus on the path-to-js-file.js file that contains the code shown below. Any action such as a click, scroll, input change, etc. will trigger this code.

There are different ways to start an AJAX request in jQuery.

  1. $.ajax()   
  2. $.get()
  3. $.post()

In line number 4 and 9,

myObj.ajaxurl
myObj.ajaxurl and
myObj.nonce
myObj.nonce
is derived from line 7 in figure 1.

The data at line number 6 has three properties. Data, which we will use in the callback function. This data could be a selected value, an input value, the whole form, etc.

Second is action we would take and its reference. The last is the nonce that which can be a custom name.

Once the data is received you are free to use the DOM the way you wish. 

Now, let’s catch this request with the

wp_ajax
wp_ajax API

The hooks and function naming convention should be in the

action_name
action_name format. For example,
wp_ajax_action_name, wp_ajax_nopriv_action_name and action_name_callback
wp_ajax_action_name, wp_ajax_nopriv_action_name and action_name_callback
function. As shown in line 8 of figure 2, this action property is mandatory and important in the data object in the javascript file.

I have written the hooks and the callback function to return the processed data in PHP as shown in figure 3.
Reiterating that this is the old method of calling AJAX and not recommended now.

The new way of AJAX

Now, let’s look at the modern way of AJAX in WordPress using REST API.

Enqueuing and localizing script(s)

The above image is not very different from figure 1, except line numbers 7 and 8. We use the same hook, action, and

wp_enqueue_script
wp_enqueue_script . However, in this case, we are passing different values in the
wp_localize_script
wp_localize_script
functions as compared to the previous one.

Here, I have used the rest_url() function to dynamically get the rest URL for this specific instance.

We also get the specific nonce to this specific instance by the

wp_create_nonce( 'wp_rest' )
wp_create_nonce( 'wp_rest' )

In the old way, you could specify a custom name for the nonce. However, now it must be written as ‘

wp_rest
wp_rest ’. 

New Way of jQuery Call

In line 3 in the above image, our URL is different. It is now a combination of

myObj.restURL
myObj.restURL and the endpoint which we created and registered with the rest API. The query reaches this endpoint instead of reaching
admin-ajax.php
admin-ajax.php
.

At line number 5 we inject the header request in the key-value format.

X-WP-Nonce
X-WP-Nonce is the key and
myObj.restNonce
myObj.restNonce
is the value. This allows us the flexibility to not deal with the nonce in the callback function. The rest API will now verify the nonce.

In the data part, you can pass as much data as is present in the key-value format.

Once the data is received you are free to use the DOM the way you wish.

PHP using REST API endpoint

In the above diagram from line number, 2 to 7, show the addition of the hook rest_api_init. This allows us to register our custom rest endpoint.

The register_rest_route function has three parameters baseUrl, endpoint, and array with two properties methods and a callback. The callback contains the name of the callback function.

Here I have written the

restAPI_endpoint_callback()
restAPI_endpoint_callback() function which processes the required data or may accept the query and return the data.
This sums up the modern way of using AJAX in WordPress using REST API.If you liked reading this post, here are a few more that may interest you,

Share this post