How to use AJAX in WordPress theme

In this article, we are going to learn what is AJAX ( Asynchronous JavaScript And XML ) and how to implement it with WordPress. WordPress’s Page / Post autosave is one of the great examples of Ajax or WordPress Image Uploader is another great example.

What is Ajax?

AJAX ( Asynchronous JavaScript And XML ) is the most popular technique in web development and widely used by many popular web applications like Amazon, etc. Ajax is the technology to send asynchronous requests to the server or in simple words to send and receive the data without reloading the web browser.

Implement Ajax with WordPress

We are going to use the Ajax with jQuery ( Popular JavaScript Library ) which is already used in WordPress. There is another reason to use jQuery for Ajax because we don’t need to take care that is the Ajax is supported or not for the web browser.

Step 1 – Create JavaScript File

The first step is to create a JavaScript file at your theme or plugin directory. It is a best practise to keep the CSS or JavaScript files separated. We are going to create our file in theme directory like twentytwenty/assets/js/custom.js.

Step 2 – Add JQuery Codes

The next step is to open the custom.js file and add your jQuery codes.

(function($) {
    $(document).ready(function() {
        // Your Javascript Codes is here
    });
})(jQuery);

Don’t confuse with (function($) {})(jQuery); it is a self-executable function that takes the jQuery as an argument. Otherwise, our javascript file will through the jQuery or $ is not defined issue. Later, we put our jQuery codes inside the $( document ).ready() becuase it will only run once the page Document Object Model (DOM) is ready to execute JavaScript codes.

Step 3 – Register JavaScript File with WordPress

The next step is to register your JavaScript file with WordPress. WordPress has the wp_enqueue_script() function to attach the JavaScript file. Let’s use wp_enqueue_script() with wp_enqueue_scripts action hook.

add_action( 'wp_enqueue_scripts', 'wp734_register_scripts' );
function wp734_register_scripts() {
    wp_enqueue_script( 
	    'custom-script', 
	    get_stylesheet_directory_uri() . '/assets/js/custom.js', 
	    array( 'jquery' ) 
    );
}

This is how we attach our JavaScript file. But there are some cases when we need to send some external data to our JavaScript file and this is where we use the wp_localize_script() function. Let’s modify our previous codes.

add_action( 'wp_enqueue_scripts', 'wp734_register_scripts' );
function wp734_register_scripts() {
    wp_register_script( 
	    'custom-script', 
	    get_stylesheet_directory_uri() . '/assets/js/custom.js', 
	    array( 'jquery' ) 
    );

    wp_localize_script( 
        'custom-script', 
        'OBJ', 
        array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))
    );

    wp_enqueue_script('custom-script');
}

The wp_localize_script() function takes 3 arguments i.e handler ( custom-script ), Object ( OBJ ) and the array data. Later we can use this array data with the help of the defined object i.e. OBJ.

Step 4 – Make Ajax Request

Now it’s time to create your first Ajax request. Open the custom.js file and add the following codes.

(function($) {
    $(document).ready(function() {
		
        $("#some_id").click( function(e) {
            e.preventDefault();

            $.ajax({
                type : "post",
                dataType : "json",
                url : OBJ.ajaxurl,
                data : { 
                    action: "my_ajax_action"
                },
                success: function(response) {
                    if( response.type == "success" ) {
                        // Success Message
                    }
                    else {
                        // Error on Failure.
                    }
                }
            });
        });
    });
})(jQuery);
<button type="button" id="some_id">Send Request</button>

Let’s send an Ajax request on a button click.

So, when we click on this button our defined JavaScript code gets executed and will send the ajax request to https://domain.com/admin/admin-ajax.php. But this is not enough. We have to define an action hook to handle the ajax request. If you noticed that we have defined an action while defining the data in our ajax request.

data: {
    action: 'my_ajax_action', 
    .....
    .....
}

This is the name of the action that we have to define and will handle our ajax request.

add_action( 'wp_ajax_my_ajax_action', 'wp343_handle_ajax' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'wp343_handle_ajax' );
function wp343_handle_ajax() {
    ....
    ....
}

The wp_ajax_{$your_action} will submit your request to admin-ajax.php file. The wp_ajax_nopriv_{$your_action} will execute for the users that is not logged in. That’s why we defined both of the actions so that it will work for both frontend and the logged-in users.

I hope you guys enjoyed this article and if you like this article, then please follow us for more interested and helpful tutorials. You can follow us on Facebook and Twitter.