« Back to News

A modern way of AJAX in WordPress using REST API

A quick Google search reveals that the most common way of calling AJAX in WordPress still uses 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.

how ajax works
Source: https://github.com/processing/p5.js/wiki/Loading-external-files:-AJAX,-XML,-JSON

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. This is simply for reference and should not be used. 

Enqueuing and localizing script(s)

Mostly this code is present infunctions.phpfile.

ajax in wordpress
Figure 1

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.ajaxurlormyObj.nonce

In line 9 the 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()
ajax in wordpress
Figure 2

In line number 4 and 9, myObj.ajaxurlandmyObj.nonceis 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 thewp_ajaxAPI

ajax in wordpress
Figure 3

The hooks and function naming convention should be in theaction_nameformat. For example, wp_ajax_action_name, wp_ajax_nopriv_action_name and action_name_callbackfunction. 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)

ajax in wordpress
Figure 4

The above image is not very different from figure 1, except line numbers 7 and 8. We use the same hook, action, andwp_enqueue_script. However, in this case, we are passing different values in thewp_localize_scriptfunctions 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 thewp_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’. 

New Way of jQuery Call

ajax in wordpress
Figure 5

In line 3 in the above image, our URL is different. It is now a combination ofmyObj.restURLand the endpoint which we created and registered with the rest API. The query reaches this endpoint instead of reachingadmin-ajax.php.

At line number 5 we inject the header request in the key-value format. X-WP-Nonceis the key andmyObj.restNonceis 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

ajax in wordpress
Figure 6

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 therestAPI_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.

Leave a Reply

About the Writer

  • Gurushant Upase

    Gurushant has more than a decade of development experience across a variety of domains and languages. He has a Masters degree in Computer Science from Pune University and is a Lead Software Developer at Synerzip.