简体   繁体   中英

Dynamic Drop Down lists using ajax, sql and php

I have a code which is working well. It populates the dropdowns dependent upon the previous list but there is a problem. In the html form in the <option value =""> field it displays "id" which is a numeric value instead of "name". Can someone please tell me how it can display "name" instead of the value. The actual problem is that it when it saves data in the sql database, it stores the corresponding "id" of the country or the state or city rather than its "name".

This is the code that I am using. I have tried changing the last line in ajax.php echo "<option value='$entity_id'>$enity_name</option>"; to echo "<option value='$entity_name'>$enity_name</option>"; but then the dynamic dropdowns do not work as they are dependent upon "id". Many thanks for your help.

ajax.php

<?php
    /* File : ajax.php
     * Author : Manish Kumar Jangir
    */
    class AJAX {

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


        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 * FROM countries";
                    $this->_fields = array('id','country_name');
                    break;
                case 'state':
                    $this->_query = "SELECT * FROM states WHERE country_id=$id";
                    $this->_fields = array('id','state_name');
                    break;
                case 'city':
                    $this->_query = "SELECT * FROM cities WHERE state_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;

?>

index.html

<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.5.2.min.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 using Ajax and Jquery</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>

You could get the script to do what you want by

  1. showing the id as a data attribute. --> Ajax->show_result()
  2. using that attribute for the id parameter in the ajax call. --> load_options()
  3. pass the whole <option> element to load_options()

this.value is wrong for the ajax query with the cahages blow because it is a name, but this still has the id as a data attribute.

<select id="country" name="country" 
        onchange="load_options(this, 'state');">
    <option value="">Select country</option>
</select>

since the id parameter is the option element from the form, we need to compensate to get the id correct.

function load_options(id,index){
...
that = $(id).find(":selected");
id = that.data('realid');

$.ajax({
    url: "ajax.php?index="+index+"&id="+id,
...

let the value attribute hold name, but keep the id.

public function show_result(){
...
    while ($result = mysql_fetch_array($query)){
        ...
        printf( '<option data-realid="%s" value="%s">%s</option>',
               $entity_id,
               $enity_name,
               $enity_name );

This should answer your question, and depending on how the form is submitted and stored, it may solve your problem. I doubt it however, because the part you neglected to show us is likely to expect an id for the state and city and not their names.

My english is not good ,so i will just write some things i have got from you.

1: You want to get a dropdown list depend on the index
2: You want to shown selected options depend on the id

FirstLy , Your codes is terrible. The php codes just try to get the data you need, why did you mixed with html?

Let us try to solve the first proplem, get a dropdown list. You should just let the php code to get the data you need, so you'd better modified your php function show_result, I would like to write like this:

public function show_result(){
        $tmpData = array();
        $i = 0;
        $query = mysql_query($this->_query);
        while($result = mysql_fetch_array($query)){
            $id = $result[$this->_fields[0]];
            $enity_name = $result[$this->_fields[1]];
            $tmpData[$i]['id'] = $id;
            $tmpData[$i]['name'] = $enity_name;
        }
        return $tmpData;   //here it saves data which you want to shown in drop down list 
    }

then in the end of file ajax.php,

 $obj = new AJAX;
 echo json_encode($obj->show_result());

Then in the js script, try to parse the data which you get from ajax.php and it is a json string, it contains the ids and names. produce the options of the dropdown selector here.

    function load_options(id,index){
    $("#loading").show();
    if(index=="state"){
        $("#city").html('<option value="">Select city</option>');
    }
    $.ajax({
        url: "ajax.php?index="+index,  //do not pass id 
        complete: function(){$("#loading").hide();},
        success: function(data) {
            var jsonObj = eval('('+data+')');
            var selected = false;
            var options = '';
            for(jsonObj in eachData){
             if(eachData.id == id)
               selected = true;  //  shown selected if it's the right option you want to see
             options +=  '<option                                                 value="'+eachData.id+'"'+selcted?"selected":""+'>'+eachData.name+'</option>';
             selected = false;
            }
            $("#"+index).html(options);
        }
    })
}

then you will get a drop down list as your wish. I just write these codes to guide you and i did not debug and test them , just try the ways: get data from php, shown them as html in page.

So that's all. And again sorry for my terrible english( I speak chinese well :) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM