How to Use jQuery Ajax in WordPress

Do you want to learn how to use Ajax in WordPress? Beginners always find difficulties in using Ajax with WordPress. In this article, we take a live example and show you how one can make use of Ajax in WordPress. We use jQuery to integrate Ajax with WordPress.

Ajax(Asynchronous JavaScript And XML) allows a web page to update asynchronously. It means data can be sent and retrieved from a server asynchronously without interfering with the display and behavior of the existing page. With Ajax, you can change small or large parts of the page without refreshing it. It helps to improve user experience and at the same time saves an extra load on the server.

Ajax has become extremely popular in web development. Most websites prefer using Ajax to load the content dynamically. Sometimes in web development, you must have to use Ajax without any second option.

Getting Started

Implementing Ajax in WordPress is easy and straightforward. Here we will demonstrate it with an example. I take a flow of country and state dropdowns. When the user selects a country from the dropdown, all states assigned to the selected country should be populated in the state dropdown. We will incorporate it through the below steps.

  • Once the user selects the country, an Ajax call initiates.
  • On the server side, it receives a country’s id and runs a query to fetch its states.
  • Build a state dropdown and return it to the frontend.
  • Load the HTML(response containing state dropdown) using jQuery.

Create Database Table

To achieve it we require 2 tables – wp_countries and wp_states. In these tables, I keep the one-to-many relationship between countries and states.

Run the below SQL statements to create these tables and also add some entries in them.

CREATE TABLE `wp_countries` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `wp_countries` (`id`, `name`) VALUES
(1, 'India'),
(2, 'China');

CREATE TABLE `wp_states` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) NOT NULL,
 `cid` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `wp_states` (`id`, `name`, `cid`) VALUES
(1, 'Maharashtra', 1),
(2, 'Gujarat', 1),
(3, 'Fujian', 2),
(4, 'Yunnan', 2);

Build Country Dropdown

Once you are ready with the database tables, build the country dropdown pre-filled with countries. You can place the code for it in your page template.

<?php
global $wpdb;
$arr_countries = $wpdb->get_results( "SELECT id, name FROM ".$wpdb->prefix."countries" );
?>
<div class="ajax-container">
    <select name="countries" class="countries">
        <option value="">--SELECT COUNTRY--</option>
        <?php foreach ( $arr_countries as $country ) : ?>
            <option value="<?php echo $country->id; ?>"><?php echo $country->name; ?></option>
        <?php endforeach; ?>
    </select>
    <div class="load-state"></div><!-- load states in this container -->
</div>

I have given the countries class to the select tag to get the value of the chosen option using jQuery. I also added an empty div with a class load-states to which the state dropdown will append after receiving a response from Ajax.

Integrate jQuery Ajax in WordPress

Next, we use jQuery to give an Ajax call and utilize the response received from the server. For this, we require the JavaScript file. Create a custom.js file inside the js directory of your active theme. Add this custom.js in the WordPress environment using the wp_enqueue_scripts action. The below code will go inside functions.php.

function blog_scripts() {
    // Register the script
    wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true );
 
    // Localize the script with new data
    $script_data_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'security' => wp_create_nonce( 'load_states' ),
    );
    wp_localize_script( 'custom-script', 'blog', $script_data_array );
 
    // Enqueued script with localized data.
    wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'blog_scripts' );

To custom.js we are passing 2 values.

  • ajaxurl : Each WordPress installation has one Ajax endpoint. We have to call the admin-ajax.php URL to accomplish the Ajax request.
  • security : We are passing a nonce with this variable to avoid CSRF attacks.

When the user chooses a country, a change event occurs. With this occurrence, we get the option value and send the Ajax request to the server side.

custom.js

jQuery(function($) {
    $('body').on('change', '.countries', function() {
        var countryid = $(this).val();
        if(countryid != '') {
            var data = {
                'action': 'get_states_by_ajax',
                'country': countryid,
                'security': blog.security
            }
 
            $.post(blog.ajaxurl, data, function(response) {
                 $('.load-state').html(response);
            });
        }
    });
});

Notice the action value in the data array. This get_states_by_ajax value is used to call the server-side PHP function. In order to call this PHP function through admin-ajax.php, add the below 2 lines to your functions.php.

add_action('wp_ajax_get_states_by_ajax', 'get_states_by_ajax_callback');
add_action('wp_ajax_nopriv_get_states_by_ajax', 'get_states_by_ajax_callback');

The ‘wp_ajax_{action}’ fires the Ajax action which refers to the callback function. The name of this callback function is passed as the second parameter in the above statements. The ‘wp_ajax_nopriv_{action}’ executes Ajax action for users that are not logged in.

Build State Dropdown

In the get_states_by_ajax_callback method, we will fetch states by country and build the state dropdown. You can define this method in the functions.php file.

<?php
function get_states_by_ajax_callback() {
    check_ajax_referer('load_states', 'security');
    global $wpdb;
    $arr_states = $wpdb->get_results( $wpdb->prepare( "SELECT id, name FROM ".$wpdb->prefix."states WHERE cid = %d", $_POST['country'] ) );
    ?>
    <?php if ( $arr_states ) : ?>
        <select>
            <?php foreach ($arr_states as $state) : ?>
                <option value="<?php echo $state->id; ?>"><?php echo $state->name; ?></option>
            <?php endforeach; ?>
        </select>
    <?php endif; ?>
    <?php
    wp_die();
}

Using the check_ajax_referer method we are validating a nonce. The script will execute only if the nonce is valid.

Now, the response of the get_states_by_ajax_callback method will send it back to JavaScript. This response will be appended to the div container having class load-state.

Go to your page and choose the country. You should see the state dropdown appearing for the selected country. All this operation will be done through Ajax without page refreshes.

I hope you understand how to use Ajax in WordPress. Following this technique, you can now integrate different functionalities through WordPress Ajax. We discussed the basic example in this tutorial. If you want to see more advanced examples using Ajax, refer to the below tutorials.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

22 thoughts on “How to Use jQuery Ajax in WordPress

  1. Hi!
    Thanks for the guide. Very easy to understand!

    I wonder if it is possible to apply this logic to a form plugin like Ninja Forms. I have two select fields with countries and states in my site with ninja forms, but dont know how to populate dynamically. :/

  2. Hi,
    Nice script, and thanks a lot for it.
    But if I have two identic forms with same select . countries and div load-states, how do i make them work independently?
    Thanks.

      1. I wouldn’t want to duplicate the whole script for that.
        I want ot have an “add” button that would dynamically add a form and the script to work independently for any of the forms.
        Do you have any idea?
        Thanks.

  3. Clear and effective description – thank you so much! Regarding lalom’s question as to where the code must be stored: the first PHP code, the country selection, is part of the code for the post/page. The jQuery code goes in the /js/custom.js file as described by the author. The remaining PHP code, the blog_scripts function, the add_action statements and the get_states_by_ajax_callback function go in the theme’s functions.php file, and must be in that order.

    1. thats what I thought but nothing seems to be happening ……..
      my page is not for drop down put to display table information via the html table on the page .
      I’m not sure why this is not working my class in the div is the same as the I used in the custom.js file
      the only thing I am doing is using a plug in to create the page is this an issue the plug in isPage Builder by SiteOrigin any help would be appreciated

  4. can we write custom file instead admin-ajax.php custom plugin file inn ajax url then what will be action hook for it?

  5. Hi , can you show me how to apply jquery with ajax for three condition like Country, state, city in dependent dropdown
    Appreciate your good work.
    Thanks in advance.

  6. Please add Cities in addition to Countries and States especially to illustrate how the jQuery code is modified to handle this additional dropdown. Also there may be an error in the dropdown code itself, move the php closing tag “?>” from the end at line 14 to line 4. And https://jsfiddle.net may be of help for testing and demos.

  7. I really like this implementation, really clean and straightforward. The only thing I find it a bit confusing is to know where to put each piece of code. In my case, I want to do this inside a plugin, so I’ll give it a shot and come back with my findings. Regards and thank you.

  8. Hi Artisans
    let say I have a second value to be retrieved from a table.
    Your function is working fine till we have to populate the value but then how can i populate also another input type hidden or number?
    thanks

    1. You will use the same logic like states drop-down. Let’s say you have one more column City in your table. Then only change will be in a query. And you will place text field for the city after the states drop-down in the same form.

      1. I explain you better my issue.
        I have 3 tables, 1 with category, 1 with products and 1 with measure and weight.
        What I need to do is:
        1st I select category (this is ok)
        2nd I select product (this is ok)
        3rd I select measure (this is ok), in this final stage I need to retrieve also the weight for the measure. If i do that inside the foreach loop will only return the last value but I need the extact weight meant for that specific measure. Any help ?
        Thanks for your support.

      2. solved below issue.
        Though, any idea how to submit for, it returns 404 page.
        I insert in option value two data, 1) the name of category 2) the id.
        I am exploding the string created to retrieve data i need, all working fine except that when I do the submit it return 404 error page.

  9. Hi Artisans, I saw your tutorial about “How To Use jQuery Ajax In WordPress” in your youtube channel , can you please send zip file for code.
    Appreciate your good work.
    Thanks in advance.

Leave a Reply

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