How To Use Ajax With jQuery 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
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 } ?>
  </select>
  <div class="load-state"></div>
</form>
?>
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<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) {
          $('.load-state').html(response);
        });
      }
    });
  });
</script>
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.
1
2
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 ) {
    ?>
    <select>
      <?php
      foreach ($aStates as $state) {
        ?>
        <option value="<?php echo $state->id; ?>"><?php echo $state->state_name; ?></option>
        <?php
      }
      ?>
    </select>
    <?php
  }
  wp_die();
}
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’.
Source Link: Click Here

Leave a Reply