How to send AJAX request in the WordPress

In this article we will talk about the AJAX technology, which allows developers to build dynamic web sites or applications. It's very popular and often used when making JavaScript code for the WordPress content management system.

You may read the following information and see what are the benefits of this technology, why it makes sense to integrate it into your code. Also, you can review examples and detailed specifications of the WordPress API functions related to the AJAX.

What is AJAX?

The term "AJAX" stands for "Asynchronous JavaScript and XML". This is a set of rules and programming patterns that allow to make asynchronous calls from the client to the server.

The JavaScript code that is compliant with this model will run as a background thread for the active window in the browser. The page will not be reloaded, and all the interaction with the back-end site is hidden from the user.

Advantages of using the AJAX technology

The AJAX technology has made a massive impact on the web browsing experience. There are many web sites that contain asynchronous dynamic forms, file upload sections, image editors or similar features that are loaded with help of AJAX within the same web page.

As a result, you may consider using this technology in your next project. The list of advantages is provided below, however, it's not final and you may find different reasons to use the AJAX in the code.

Asynchronous code execution

You may initiate several AJAX requests and they will execute in parallel and the result will be returned to the client as soon as the server finishes processing the data. Such a technique can be used in complex web applications, such as CRM, ERP or any other similar products.

Less load on a server

The standard workflow is when the user opens the web page and the browser loads all additional resources over the network, such as images, CSS or JS files, fonts and other static resources. However, when making a request to the server via AJAX call, all those files are not loaded, which may result in an improved performance.

Better user experience

For example, you can use the AJAX technology to make dynamic popup modal windows that appear in a browser after clicking on a specific button. And that modal content will be shown much faster than using the standard way, when the page URL is switched in the browser and all the content is fetched from the remote server.

In most cases, typical AJAX web applications are more attractive for the users, since the content is changed quickly, there may be no visual shifting of the applicable HTML elements.

Disadvantages of the AJAX technology

As you see, there are many benefits of using the asynchronous JavaScript code. But, such a method may not be suitable in specific cases.

For example, the client to server communication must be fast and efficient. If the user closes the browser window, then the AJAX request may not complete and some important data can be lost. As a developer, you have to write a robust and well designed code that handles all the possible critical situations.

And sometimes it may be difficult to debug such a code, the engineers must have strong expertise in JavaScript language or any applicable web frameworks.

Also, security is another concern that you must take into account. The back-end code should be reliable, you may need to verify the user data, escape unsafe values, etc.

WordPress actions that allow to handle AJAX requests

If you are making AJAX code for the WordPress CMS then you have to set up actions that will be called on each request from client to the server. Please review the specification below.

wp_ajax_(action)
wp_ajax_nopriv_(action)

The first action is executed by WordPress for authorized users, while the second is executed for anonymous users that have not logged in to the system.

Such a design allows you to have separated logic for each group of site visitors. You can make a robust code by running privileged functionality only in a secure manner by attaching it to the action that can ensure that the user is authenticated.

Below, you can see a sample of attaching AJAX action.

add_action( 'wp_ajax_sample', 'my_action_sample' );

function my_action_sample() {
    // Add a code below to execute it for logged-in users.

    // Stop execution
    wp_die();
}

Respectively, you can see in the following demo how to add action for a non-privileged version of the AJAX call.

add_action( 'wp_ajax_nopriv_sample', 'my_nopriv_action_sample' );

function my_nopriv_action_sample() {
    // Add a code below to execute it for non-authorized site visitors.

    // Stop execution
    wp_die();
}

Client side AJAX request

Before making any requests to the server, you have to define a variable that will hold the URL of the AJAX endpoint, the most common way is to use the wp_localize_script() function for that purpose.

Please see how it can be done in the following code sample.

function theme_enqueue_scripts() {
    wp_enqueue_script( 'site-tools', get_theme_file_uri( '/js/tools.js' ), array( 'jquery' ), null, true );
    wp_localize_script( 'site-tools', 'site_tools',
        array(
            'ajaxurl' => admin_url( 'admin-ajax.php' )
        )
    );
}

add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );

On a PHP side, the admin_url() function generates the endpoint URL and transfers that value into the ajaxurl property of the site_tools object, which later can be used in JavaScript code.

Now, you can make an AJAX request to the server. Please pay attention that the "action" property of the data object must be set to the proper action name, which we've configured on a WordPress side as a part of the action name. In this specific case, that's a "sample" keyword.

jQuery( document ).ready( function( $ ) {
    $.post( {
        url: site_tools.ajaxurl,
        data: {
            'action': 'sample'
        },
        success: function( response ) {
            console.log( response );
        },
    } );
} );

Administration side AJAX request

It's much easier to write an AJAX code for the administration side of the WordPress CMS, since the ajaxurl is already defined inside of an HTML document in such a case.

If you are making a plugin, then you may omit adding the code that generates the AJAX endpoint URL. As result, the typical admin side JavaScript may look like the following:

jQuery( document ).ready( function( $ ) {
    $.post( {
        url: ajaxurl,
        data: {
            'action': 'sample'
        },
        success: function( response ) {
            console.log( response );
        },
    } );
} );

As you see, the only tiny difference is that we use the "ajaxurl" variable when calling the jQuery.post() function.

It is worth mentioning that you may need to integrate additional security checks into the source code. For example, you may consider using the check_ajax_referer() or current_user_can() functions.

How to send a status code to the client

Once execution of the server side code ends, you need to send a result and a status code to the client. Then also you have to terminate the execution of the PHP code. There is a built-in WordPress function that allows you to make this in an effective and compact way.

Please review the specification of the function that allows sending a "success" status to the client.

wp_send_json_success( $data = null, $status_code = null, $options = 0 )

Also, there is a similar function that allows sending an "error" status, see how it looks below.

wp_send_json_error( $data = null, $status_code = null, $options = 0 )

The above methods use the wp_send_json() function, which you can use in your code as well, specification is given below.

wp_send_json( $response, $status_code = null, $options = 0 )

Also, it is worth mentioning that the wp_send_json() function stops execution of the PHP code by using either wp_die() function or the "die" operator.

Difference between jQuery.post() and jQuery.ajax() functions

You may get confused if you review source code of various open source projects and see that some engineers use the jQuery.post() method, while others use the jQuery.ajax().

They are very similar and both make a request to the server. From the technical point of view, the post() method is a superset of the ajax() call. If you use the ajax() function directly, you have to specify the type of the request, for example, "POST". See how it is done if the following example:

$.ajax( {
    type: 'POST',
    url: '/wp-admin/admin-ajax.php',
    data: {
        action: 'sample',
        status: 'success'
    }
} );

It makes sense to use jQuery.post() in most cases, unless you have unusual project requirements and need to use a different type of HTTP request.

Conclusion

As you see, AJAX is not a programming language, but rather a set of rules and concepts that define how the client side code can communicate to the server. You can use this technology to build modern and attractive web applications.

The major benefit of integrating the AJAX into your codebase is that users can enjoy using more advanced and dynamic web interfaces. Forms and modal windows will render quickly, transition between HTML elements can be smooth and rapid.

Thank you for reading this article, our hope is that it was helpful for you. Do not hesitate to leave your questions or comments in the form below.

Leave a Reply

Your email address will not be published. Required fields are marked *