Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

ajax - How to make a Cascading Drop Down List in PHP using jQuery

I have database consists of countries and cities.

First Case - Successfully done:

  1. Country list gets populated in drop box on page load
  2. City list gets populated in drop box on page load - populated city list is based on the default country.

Second Case - Couldn't make it:

  1. User changes country
  2. City list will be changed according to selected country

I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.

I'm using regular PHP coding style, not Object-Oriented.

How can i do it? Any related resources will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$("#country").change(function(){
    $('#city').find('option').remove().end(); //clear the city ddl
    var country = $(this).find("option:selected").text();
    alert(country);
    //do the ajax call
    $.ajax({
        url:'getCity.php'
        type:'GET',
        data:{city:country},
        dataType:'json',
        cache:false,
        success:function(data){

        data=JSON.parse(data); //no need if dataType is set to json
         var ddl = document.getElementById('city');                      

         for(var c=0;c<obj.length;c++)
              {              
               var option = document.createElement('option');
               option.value = obj[c];
               option.text  = obj[c];                           
               ddl.appendChild(option);
              }


    },
        error:function(jxhr){
        alert(jxhr.responseText);

    }
    }); 

});

in your getCity.php

$country = $_GET['city'];

//do the db query here

$query  = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {

 if(empty($temp))
 {
   $temp=array($row['city']);
 }
 else
 {  
   array_push($temp,$row['city']);
 }

}
echo (json_encode($temp));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...