how to create a dynamic dependent select box which fetches records from database without reload the page using ajax.

here is my code. ajax-cities.php


add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
    wp_enqueue_script( 'ajax-script', plugins_url( '/cities.js', __FILE__ ), array('jquery'));
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )));

function my_action() {
$country_id = $_REQUEST['id'];
global $wpdb;
$cities = $wpdb->get_results($wpdb->prepare("SELECT * FROM city WHERE country_id='".$country_id."'",13,'gargle'),ARRAY_A);
foreach($cities as $city)
{ ?>
<option value="<?php echo $city["city_id"]; ?>"><?php echo $city["city_name"]; ?></option>
<?php }



   get_header(); ?>
    <div id="contents">
    <h1>Select Country</h1><br/><br/>
    <form name="form" method="post">
    <label>Country: </label><select name="country" class="country">
    <option>Select Country</option>
    global $wpdb;
    $countries = $wpdb->get_results($wpdb->prepare("SELECT * FROM country",13,'gargle'),ARRAY_A);
    foreach($countries as $country)
    { ?>           
    <option value="<?php echo $country["country_id"]; ?>"><?php echo $country["country_name"]; ?></option>
    <?php } ?>
    <label>City: </label><select name="city" class="city">
    <option>Select City</option>
    <?php get_footer(); ?>

but doesn't shows dependent city name.

1 Answer 1


add this two hooks at the end of your ajax-cities.php file

add_action('wp_ajax_my_action', 'my_action' );
add_action('wp_ajax_nopriv_my_action', 'my_action');
  • 1
    Please edit your answer, and add an explanation: why could that solve the problem? Also, please merge your accounts.
    – fuxia
    Commented Dec 28, 2016 at 11:13
  • Work completely.thanx
    – Jayesh
    Commented Dec 28, 2016 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.