How To Use jQuery Ajax In WordPress

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

Why We Need jQuery Ajax In Website?

Ajax(Asynchronous JavaScript And XML) allows a web page to update asynchronously. It means an exchange of data with a web server behind the scenes. Using Ajax, you can change part of a web page without refreshing a whole page. It helps to improve a user experience and at the same time saves a load on the server.

Nowadays, Ajax becomes extremely popular among the web. Websites like Facebook, Twitter, Instagram and much more are using Ajax to load the content dynamically.

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

jQuery Ajax in WordPress

Implementing WordPress Ajax is so simple actually. We will see a practical example of it. Let’s say we have tables wp_countries and wp_states. Our task is – On the selection of country display the respective states in the drop-down. In the below tables we have the one-to-many relationship between country and states.

Table Country


Table States


To build our country drop-down let’s first fetch the countries from the database and build the drop-down from it.

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

<form method="post">
  <select class="countries">
    <option value="">--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 select tag which would use in jQuery code. Also, We have added an empty div with class ‘load-states’ which will use to append state dropdown after Ajax response.

Now let’s write a jQuery code which acts as a bottleneck for our task.

<script type="text/javascript">
  var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
  jQuery(function($) {
    $('body').on('change', '.countries', function() {
      var countryid = $(this).val();
      if(countryid != '') {
        var data = {
          action: 'get_states_by_ajax',
          country: countryid,
          'security': '<?php echo wp_create_nonce("load_states"); ?>'

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

At first we declared the variable ajaxurl. This is because in WordPress each Ajax request should send to admin-ajax.php file. So we store file path in our variable. Then we declared variable with the name data. It contains parameter action. The action parameter is user-defined name which should be task-oriented. As we are fetching states so I keep the name get_states_by_ajax. Rest of the parameters are the details should send to Ajax request. As we have to pass country id we keep the parameter name as country and value for this parameter is countryid.

Now it’s time to write actual Ajax code in a WordPress way. Write the below Ajax code 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 we are writing Ajax code in WordPress. Then append the action parameter value to it. In our case it is get_states_by_ajax. So, first parameter becomes wp_ajax_get_states_by_ajax. Second parameter is a callback function in which we have to write our actual code. wp_ajax_nopriv should use when we are doing operations for front end.

All is set. Now we can write the code which will return the states in the HTML drop-down format.

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>

Above response will send to our jQuery code. And using jQuery we append the states drop-down in the div container with class ‘load-state’.

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

Related Articles

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

Recommended Tutorials For You

6 thoughts on “How To Use jQuery Ajax In WordPress

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

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

Leave a Reply

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