How to Use jQuery Ajax in WordPress

Do you want to implement jQuery Ajax in WordPress? WordPress beginners always find difficulties in using Ajax with WordPress. In this article, we study how to use Ajax in WordPress by taking a live example.

Why Need of jQuery Ajax in Website?

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

Ajax becomes extremely popular in web development. Most of the websites prefer using Ajax to load the content dynamically. In web development for a few tasks, you must have to use Ajax without any second option.

Having said that, let’s see how to use jQuery Ajax in WordPress.

Getting Started

Implementing Ajax in WordPress is easy and straight-forward. We will see a practical example of it. As an example, let’s 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. This behavior must be done by Ajax.

To achieve it you will require 2 tables – wp_countries and wp_states. In these tables, you should keep the one to many relationship between country and states. Refer to the below screenshots.

Table wp_countries


Table wp_states


Once you are ready with the data, build the country drop-down by fetching the data from the country table as follows.

global $wpdb;
$aCountries = $wpdb->get_results( "SELECT id, country FROM ".$wpdb->prefix."countries" );

<form method="post">
    <select class="countries">
        <option value="">--<?php _e('SELECT COUNTRY'); ?>--</option>
        <?php foreach ($aCountries as $country) { ?>
              <option value="<?php echo $country->id; ?>"><?php echo $country->country; ?></option>
        <?php } ?>
    <div class="load-state"></div>

We have added the class ‘countries’ to the select tag that will be used in the jQuery code to get the id of a country. I also added an empty div with class ‘load-states’ to which state dropdown will append after receiving a response from the Ajax call.

jQuery Ajax in WordPress

Next, we need to write a jQuery code that gives an Ajax call to the server and handles the response. For writing an Ajax call, you should include the JS file. Create a custom.js file inside the js directory of your active theme. Add this custom.js in WordPress environment using the below code which goes 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' );

Now, let’s write a jQuery code that gives an Ajax call and append the state dropdown to the page.


jQuery(function($) {
    $('body').on('change', '.countries', function() {
        var countryid = $(this).val();
        if(countryid != '') {
            var data = {
                'action': 'get_states_by_ajax',
                'country': countryid,

            $.post(blog.ajaxurl, data, function(response) {

Here, I declared a data variable which contains an action key. The string value for action key should be task-oriented. We are fetching states so I keep it’s name as get_states_by_ajax. Other elements of data variable are the details should send to Ajax requests. Our goal is fetching a state based on country, so I am passing country id with the key as country.

Now it’s time to execute Ajax calls in a WordPress way. Add the below 2 statements in your active theme’s functions.php file.

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');

‘wp_ajax’ is a fixed prefix while using Ajax in WordPress. Then append the action’s value to it. In our case it is get_states_by_ajax. So, the first parameter became wp_ajax_get_states_by_ajax. Second parameter is a callback function in which we have to write our actual server-side code. ‘wp_ajax_nopriv’ should be used when you are doing operations for the front end.

In the get_states_by_ajax_callback method, write the code which will return the state dropdown. You can define this method in functions.php file.

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

The response built into the code will send it back to the jQuery. This response we then append using jQuery to the div container which has class ‘load-state’.

Go to your page and choose the country. You should see the state dropdown appears for the selected country.

I hope you understand how to use Ajax on the WordPress website. Please share your thoughts and suggestions in the comment section below.

Related Articles

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

21 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?

      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?

  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 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?

    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 *