0

Good day,

I have the following dynamic drop down list. Here, if you select country from first list, relevant states will be pulled up from database at second list.

What I need to do: Right now, second drop down list is populated based on "ID" associated with first drop down list. I need it to be dependent on the "value" of first drop down list.

I would highly appreciate if someone could help me to do that.

I am new here. I would also appreciate any advice.

many thanks in advance. Ashique

SQL table structure: column1=id, column2=country_name, column3=state_name, column4=city_name

Here is the SQL code:

        CREATE TABLE IF NOT EXISTS `globe` (
  `id` int(3) NOT NULL,
  `country_name` varchar(20) NOT NULL,
  `state_name` varchar(20) NOT NULL,
  `city_name` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `globe`
--

INSERT INTO `globe` (`id`, `country_name`, `state_name`, `city_name`) VALUES
(3, 'UK', 'LT', 'london'),
(2, 'Canada', 'BC', 'vancuvar'),
(1, 'USA', 'NY', 'new york');

Here is the HTML data with Ajax:

    <html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11">
<head>
<title>Country State City Dependent Dropdown using Ajax</title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    load_options('','country');
});

function load_options(id,index){
    $("#loading").show();
    if(index=="state"){
        $("#city").html('<option value="">Select city</option>');
    }
    $.ajax({
        url: "ajax.php?index="+index+"&id="+id,
        complete: function(){$("#loading").hide();},
        success: function(data) {
            $("#"+index).html(data);
        }
    })
}
</script>
</head>
<body>
<div style="width:800px; margin:auto;padding-top:100px;">
<h1>Country,State,City dynamic dependent dropdown</h1>
<form>
        <label>Select Country</label>
        <select id="country" name="country"onChange="load_options(this.value,'state');">
            <option value="">Select country</option>
        </select>
        &nbsp;&nbsp;&nbsp;
        <label>Select State</label>
        <select id="state" name="state" onChange="load_options(this.value,'city');">
            <option value="">Select state</option>
        </select>
        &nbsp;&nbsp;&nbsp;
        <label>Select city</label>
        <select id="city" name="city">
            <option value="">Select City</option>
        </select>
        <img src="loader.gif" id="loading" align="absmiddle" style="display:none;"/>
</form>
</div>
</body>
</html>

PHP codes are saved at ajax.php file given below:

<?php

class AJAX {

    private $database = NULL;
    private $_query = NULL;
    private $_fields = array();
    public  $_index = NULL;
    const DB_HOST = "localhost";
    const DB_USER = "root";
    const DB_PASSWORD = "";
    const DB_NAME = "2";


    public function __construct(){
        $this->db_connect();                    // Initiate Database connection
        $this->process_data();
    }

    /*
     *  Connect to database
    */
    private function db_connect(){
        $this->database = mysql_connect(self::DB_HOST,self::DB_USER,self::DB_PASSWORD);
        if($this->database){
            $db =  mysql_select_db(self::DB_NAME,$this->database);
        } else {
            echo mysql_error();die;
        }
    }



    private function process_data(){
        $this->_index = ($_REQUEST['index'])?$_REQUEST['index']:NULL;
        $id = ($_REQUEST['id'])?$_REQUEST['id']:NULL;
        switch($this->_index){
            case 'country':
                $this->_query = "SELECT id,country_name FROM globe";
                $this->_fields = array('id','country_name');
                break;
            case 'state':
                $this->_query = "SELECT id,state_name FROM globe WHERE id=$id";
                $this->_fields = array('id','state_name');
                break;
            case 'city':
                $this->_query = "SELECT id,city_name FROM globe WHERE id=$id";
                $this->_fields = array('id','city_name');
                break;
            default:
                break;
        }
        $this->show_result();
    }

    public function show_result(){
        echo '<option value="">Select '.$this->_index.'</option>';
        $query = mysql_query($this->_query);
        while($result = mysql_fetch_array($query)){
            $entity_id = $result[$this->_fields[0]];
            $enity_name = $result[$this->_fields[1]];
            echo "<option value='$entity_id'>$enity_name</option>";
        }
    }
}

$obj = new AJAX;

    ?>
1
  • And your effort so far? Commented Jan 3, 2014 at 9:06

1 Answer 1

2

Your queries are all wrong. For countries, you'll list the same country multiple times if you have different cities in it. And for state and city, you're just returning the one city with the same ID as the country or state that was selected, you have to get all of them.

private function process_data(){
    $this->_index = ($_REQUEST['index'])?$_REQUEST['index']:NULL;
    $id = ($_REQUEST['id'])? (int)$_REQUEST['id']:NULL;
    switch($this->_index){
        case 'country':
            $this->_query = "SELECT id,country_name 
                             FROM globe 
                             GROUP BY country_name";
            $this->_fields = array('id','country_name');
            break;
        case 'state':
            $this->_query = "SELECT g1.id, g1.state_name 
                             FROM globe AS g1
                             JOIN globe AS g2 USING (country_name)
                             WHERE g2.id = $id
                             GROUP BY g1.state_name";
            $this->_fields = array('id','state_name');
            break;
        case 'city':
            $this->_query = "SELECT g1.id, g1.city_name
                             FROM globe AS g1
                             JOIN globe AS g2 USING (country_name, state_name)
                             WHERE g2.id = $id";
            $this->_fields = array('id','city_name');
            break;
        default:
            break;
    }
    $this->show_result();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the developed script. It was great help. Its working just great.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.