Forum Moderators: coopster

Message Too Old, No Replies

Dynamic State/City dropdowns

         

ryan_b83

7:14 pm on Apr 11, 2007 (gmt 0)

10+ Year Member



Hello, I am wondering the best way to do the dropdown menus in a form where you would choose a province/state, then it would provide you with another dropdown of medium-large cities in that province/state?

Is this AJAX required? Also is there somewhere to find the list of cities?

Thanks,
Ryan

eelixduppy

1:52 am on Apr 12, 2007 (gmt 0)



Hello Ryan,

To be quite honest with you, this question is very popular. There are tutorials for something like this online; a google search should produce some decent results. I, however, feel like spending some time sharing what I use to accomplish this. To be honest, I am not a javascript/ajax pro, but it works for me and I like it because of it's simplicity. I've added comments in there to give a general idea of what is happening. So here goes...

I have three files: index.html, combo.js, fetch.php

combo.js:


//globals
var first = "topic"; //id of first SELECT
var second = "subcats"; //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 Topic First';
ob2.disabled=1;
}
}

fetch.php


<?php
if(empty($_GET['topic'])) { # if url query is left empty, do nothing but terminate the script
exit();
}
$topic = $_GET['topic'];
$link = mysql_connect("localhost","username","password");
mysql_select_db("database_name");
#
#select records based on 'topic'
$query = "SELECT item FROM info WHERE cat = '".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['item']; #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
}
?>

index.html


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

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

</head><body>

<form action="index.html" method="post">
<table cellpadding="15px">
<tr>
<td>Topic:</td>
<td>
<select id="topic" onChange="clicked();" style="width: 200px;">
<option>Please Select</option>
<option value='fruit'>Fruits</option>
<option value='vegetable'>Vegetables</option>
<option value='meat'>Meats</option>
</select>
</td>
</tr><tr>
<td>Generated:</td>
<td>
<select id="subcats" disabled="disabled" style="width: 200px;">
<option>Select Topic First</option>
</select>
</td>
</tr>
</table>
</form>
</body></html>

And then, of course, you have to have a db setup correctly. I believe it is obvious enough how the db is setup, as it only have two columns, one for the category and one for the contents in that category. As I said, I'm no javascript guru, but this works for me.

Hope this will help out those who are having a similar issue with this. This question comes up a lot and instead of linking to other tutorials, why not have our own? ;)

Best of luck!

P.S. If you see a problem with the above script, please inform me and I will fix it. As I said, I'm no js pro ;)

eelixduppy

1:58 am on Apr 12, 2007 (gmt 0)



As a little point of reference, you may also want to take a look at some of the following links as they will also assist in creating this dynamic drop down--or understand it: :)

Also, make sure to try a google search for some results, too.

Again, good luck! :)

[edited by: eelixduppy at 7:00 am (utc) on July 23, 2007]

ryan_b83

3:02 am on Apr 12, 2007 (gmt 0)

10+ Year Member



GREAT REPLY!

Thanks alot, I myself am not a big JS guy, but i work alot with PHP/MySQL so that part shouldn't be a problem at all. Great example!

Thanks Again!

Ryan