Jump to content

[SOLVED] Dynamic Dropdown with AJAX


timmah1

Recommended Posts

This is probably the wrong forum to post in, but this is the most helpful, so here goes.

 

I have a database with all US Cities, associated with the states.

 

id state_id city

 

I have a drop-down with all the states with their ID

<select id="state" onChange="clicked();" style="width: 200px;"> 
         		 <option selected>Please Select</option>
         		 <option value="1">Alabama</option> 
	         <option value="2">Alaska</option> 
	         <option value="3">Arizona</option> 
	         <option value="4">Arkansas</option> 
	         <option value="5">California</option> 
	         <option value="6">Colorado</option> 
	         <option value="7">Connecticut</option> 
	         <option value="8">Delaware</option> 
	         <option value="9">Florida</option> 
	         <option value="10">Georgia</option> 
	         <option value="11">Hawaii</option> 
	         <option value="12">Idaho</option> 
	         <option value="13">Illinois</option> 
	         <option value="14">Indiana</option> 
	         <option value="15">Iowa</option> 
	         <option value="16">Kansas</option> 
	         <option value="17">Kentucky</option> 
	         <option value="18">Louisiana</option> 
	         <option value="19">Maine</option> 
	         <option value="20">Maryland</option> 
	         <option value="21">Massachusetts</option> 
	         <option value="22">Michigan</option> 
	         <option value="23">Minnesota</option> 
	         <option value="24">Mississippi</option> 
	         <option value="25">Missouri</option> 
	         <option value="26">Montana</option> 
	         <option value="27">Nebraska</option> 
	         <option value="28">Nevada</option> 
	         <option value="29">New Hampshire</option> 
	         <option value="30">New Jersey</option> 
	         <option value="31">New Mexico</option> 
	         <option value="32">New York</option> 
	         <option value="33">North Carolina</option> 
	         <option value="34">North Dakota</option> 
	         <option value="35">Ohio</option> 
	         <option value="36">Oklahoma</option> 
	         <option value="37">Oregon</option> 
	         <option value="38">Pennsylvania</option> 
	         <option value="39">Rhode Island</option> 
	         <option value="40">South Carolina</option> 
	         <option value="41">South Dakota</option> 
	         <option value="42">Tennessee</option> 
	         <option value="43">Texas</option> 
	         <option value="44">Utah</option> 
	         <option value="45">Vermont</option> 
	         <option value="46">Virginia</option> 
	         <option value="47">Washington</option> 
	         <option value="48">Washington D.C.</option> 
	         <option value="49">West Virginia</option> 
	         <option value="50">Wisconsin</option> 
	         <option value="51">Wyoming</option> 

      </select> 

 

When a state is clicked, I want it to populate the City dropdown, but it is not working, the City dropdown is blank.

 

Can anybody look at the code and tell me what I'm doing wrong?

 

test.php

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
<head> 
   <title>testing</title> 


<script type="text/javascript" src="combo.js"></script> 


</head><body> 


<form action="test.php" method="post"> 
<table cellpadding="15px"> 
<tr> 
   <td>State:</td> 
   <td> 
      <select id="state" onChange="clicked();" style="width: 200px;"> 
         		 <option selected>Please Select</option>
         		 <option value="1">Alabama</option> 
	         <option value="2">Alaska</option> 
	         <option value="3">Arizona</option> 
	         <option value="4">Arkansas</option> 
	         <option value="5">California</option> 
	         <option value="6">Colorado</option> 
	         <option value="7">Connecticut</option> 
	         <option value="8">Delaware</option> 
	         <option value="9">Florida</option> 
	         <option value="10">Georgia</option> 
	         <option value="11">Hawaii</option> 
	         <option value="12">Idaho</option> 
	         <option value="13">Illinois</option> 
	         <option value="14">Indiana</option> 
	         <option value="15">Iowa</option> 
	         <option value="16">Kansas</option> 
	         <option value="17">Kentucky</option> 
	         <option value="18">Louisiana</option> 
	         <option value="19">Maine</option> 
	         <option value="20">Maryland</option> 
	         <option value="21">Massachusetts</option> 
	         <option value="22">Michigan</option> 
	         <option value="23">Minnesota</option> 
	         <option value="24">Mississippi</option> 
	         <option value="25">Missouri</option> 
	         <option value="26">Montana</option> 
	         <option value="27">Nebraska</option> 
	         <option value="28">Nevada</option> 
	         <option value="29">New Hampshire</option> 
	         <option value="30">New Jersey</option> 
	         <option value="31">New Mexico</option> 
	         <option value="32">New York</option> 
	         <option value="33">North Carolina</option> 
	         <option value="34">North Dakota</option> 
	         <option value="35">Ohio</option> 
	         <option value="36">Oklahoma</option> 
	         <option value="37">Oregon</option> 
	         <option value="38">Pennsylvania</option> 
	         <option value="39">Rhode Island</option> 
	         <option value="40">South Carolina</option> 
	         <option value="41">South Dakota</option> 
	         <option value="42">Tennessee</option> 
	         <option value="43">Texas</option> 
	         <option value="44">Utah</option> 
	         <option value="45">Vermont</option> 
	         <option value="46">Virginia</option> 
	         <option value="47">Washington</option> 
	         <option value="48">Washington D.C.</option> 
	         <option value="49">West Virginia</option> 
	         <option value="50">Wisconsin</option> 
	         <option value="51">Wyoming</option> 

      </select> 
   </td> 
</tr><tr> 
   <td>City:</td> 
   <td> 
      <select id="city" disabled="disabled" style="width: 200px;"> 
         <option>Select State First</option> 
      </select> 
   </td> 
</tr> 
</table> 
</form> 
</body></html> 

 

fetch.php

<?php 
if(empty($_GET['state'])) { # if url query is left empty, do nothing but terminate the script 
   exit(); 
} 
$topic = $_GET['state']; 
$link = mysql_connect("localhost","xx","xx"); 
mysql_select_db("xx"); 
# 
#select records based on 'topic' 
$query = "SELECT id, city FROM cities WHERE state_id = '".mysql_real_escape_string($topic)."'";  
$result = mysql_query($query); 
# 
if($result) { #make sure the query was successful 
   $items = array(); 
# 
   while($row = mysql_fetch_array($result)) { 
      $items[] = $row['city']; #push all of the results into an array 
   } 
# 
$string = implode(',',$items); #implode the results separated by commas 
echo $string; #here we echo the string to the browser; this is what the javascript will be receiving 
} 
?> 

 

combo.js

//globals 
var first = "state"; //id of first SELECT 
var second = "city"; //id of second SELECT 
// 
function sendRequest(url,params,HttpMethod) { 
if(!HttpMethod) { //check if http method is defined, if not, set it to GET 
   HttpMethod="GET"; 
} 
// 
// initialize request object 
req=null; 
if(window.XMLHttpRequest){ 
   req=new XMLHttpRequest; //mozilla/safari 
} else if(window.ActiveXObject){ 
   req=new ActiveXObject("Microsoft.XMLHTTP"); //internet explorer 
} 
// 
//define callback handler 
if(req) { 
// 
   req.onreadystatechange=onReadystate; 
   req.open(HttpMethod,url,true); 
   req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
   req.send(params); 
} 
} 
// 
function onReadystate() { 
// 
var ready=req.readystate; 
var data=null; 
if(ready==4){ //check ready state 
   data=req.responseText; //read response data 
   var items = data.split(','); 
   var length = items.length; 
   for(var i = 0; i < length; i++) { 
      var childEl = document.createElement('option'); //create option 
      var El = document.getElementById(second); 
      El.appendChild(childEl); //then append it to the second dropdown list 
      childEl.value = items[i]; 
      childEl.innerHTML = items[i]; 
   } 
} 
} 
// 
function clicked() { 
// 
var el = document.getElementById(first); 
var ob2 = document.getElementById(second); 
var selected = el.selectedIndex; 
// 
while(ob2.hasChildNodes()) { //removes items from dropdown if some already exist 
   ob2.removeChild(ob2.firstChild); 
} 
if(selected!= 0) { //if they choose something other than the first select-->"Select topic first" 
   sendRequest('fetch.php?topic='+el.options[selected].value); 
   ob2.disabled=0; 
} else { //otherwise add the Select Topic First option and disable it 
   var childEl = document.createElement('option'); 
   ob2.appendChild(childEl); 
   childEl.innerHTML = 'Select State First'; 
   ob2.disabled=1; 
} 
} 

 

Thanks in advance

Link to comment
Share on other sites

The logic looks okay.. (I know it seams like i'm passing the buck but it seams like a JS problem)

 

try opening fetch.php via the browser with the state and check the output..

fetch.php?state=1

fetch.php?state=2

fetch.php?state=3

 

assuming thats okay it would be a JS problem try adding an alert (see below)

function onReadystate() {
//
var ready=req.readystate;
var data=null;
if(ready==4){ //check ready state
alert('I GOT HERE');//<--------------HERE
   data=req.responseText; //read response data
   var items = data.split(',');
   var length = items.length;
   for(var i = 0; i < length; i++) {
      var childEl = document.createElement('option'); //create option
      var El = document.getElementById(second);
      El.appendChild(childEl); //then append it to the second dropdown list
      childEl.value = items[i];
      childEl.innerHTML = items[i];
   }
}
} 

 

If after selecting a option from the first box you get the alert then the problem would be the JS directly below it (i assume its in that part)

Also try it on another Browser

 

Hope that helps

Link to comment
Share on other sites

sniperscope,

I'm not well versed in javascript, so that's why I don't do it in javascript.

 

MadTechie,

I tried your sample, and got nothing, then I put an alert on the bottom

function clicked() { 
// 
var el = document.getElementById(first); 
var ob2 = document.getElementById(second); 
var selected = el.selectedIndex; 
// 
while(ob2.hasChildNodes()) { //removes items from dropdown if some already exist 
   ob2.removeChild(ob2.firstChild); 
} 
if(selected!= 0) { //if they choose something other than the first select-->"Select topic first" 
alert('I GOT HERE1');//<--------------HERE
   sendRequest('fetch.php?topic='+el.options[selected].value); 
   ob2.disabled=0; 
} else { //otherwise add the Select Topic First option and disable it 
   var childEl = document.createElement('option'); 
   ob2.appendChild(childEl); 
   childEl.innerHTML = 'Select State First'; 
   ob2.disabled=1; 
} 
} 

 

And I received that alert.

 

I also did this before posting

fetch.php?state=1

fetch.php?state=2

fetch.php?state=3

 

to make sure something was being grabbed, and it shows everything correctly, so to be honest, I have no idea

why this isn't working

Link to comment
Share on other sites

did you put the alert in the place i said as your post has the alert in a different place!

 

if(selected!= 0) { //if they choose something other than the first select-->"Select topic first"
alert('I GOT HERE1');//<--------------HERE

 

if(ready==4){ //check ready state
alert('I GOT HERE');//<--------------HERE

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.