Thursday, July 19, 2007

Ajax Triple Dropdown with States Cities Database

Ajax Dropdown Menu it's make easy for user to use interface. When you choose first dropdown menu data in second dropdown will be filter and data related in first dropdown will be show automatic

For This Example Code is PHP and Database is MySQL

Example : Stated and Cities

1. Create Dropdown Menu (state_dropdown.php)


<?
echo "<form name=sel>\n";
echo "States : <font id=states><select>\n";
echo "<option value='0'>============</option> \n" ;
echo "</select></font>\n";

echo "Cities : <font id=cities><select>\n";
echo "<option value='0'>=== none ===</option> \n" ;
echo "</select></font>\n";
?>

<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};

function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "state.php?data="+src+"&val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}

window.onLoad=dochange('states', -1); // value in first dropdown
</script>



2. Select States and Cities to Show in Dropdown (state.php)


<?
//set IE read from page only not read from cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");

header("content-type: application/x-javascript; charset=tis-620");

$data=$_GET['data'];
$val=$_GET['val'];

//set database
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");

if ($data=='states') { // first dropdown
echo "<select name='states' onChange=\"dochange('cities', this.value)\">\n";
echo "<option value='0'>==== choose state ====</option>\n";
$result=mysql_db_query($dbname,"select `id`, `state` from states order by `state`");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='cities') { // second dropdown
echo "<select name='cities' >\n";
echo "<option value='0'>====choose cities ====</option>\n";
$result=mysql_db_query($dbname,"SELECT `id`, `city` FROM cities WHERE `state_id` = '$val' ORDER BY `city` ");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}
echo "</select>\n";
?>




See Example : States and Cities DropDown
Download Source code : ajax_dropdown.rar
mirror : ajax_dropdown.rar

( Please don’t directly link to the file… thank you )

Example 2 : This is Triple Ajax Dropdown Menu - Province - Ampher - Tumbon in Thailand

1. Create Dropdown Menu (locale_dropdown.php)

<? echo "<form name=sel>\n"; echo "จังหวัด : <font id=province><select>\n"; echo "<option value='0'>============</option> \n" ; echo "</select></font>\n";
echo "อำเภอ : <font id=amper><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; echo "ตำบล : <font id=tumbon><select>\n"; echo "<option value='0'>==== ไม่มี ====</option> \n" ; echo "</select></font>\n"; ?>

<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};

function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //รับค่ากลับมา
}
}
};
req.open("GET", "locale.php?data="+src+"&val="+val); //สร้าง connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=tis-620"); // set Header
req.send(null); //ส่งค่า
}

window.onLoad=dochange('province', -1);
</script>


2. Select Province Ampher Tumbon to Show in Dropdown (locale.php)

<?
//กำหนดให้ IE อ่าน page นี้ทุกครั้ง ไม่ไปเอาจาก cache
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");

header("content-type: application/x-javascript; charset=tis-620");

$data=$_GET['data'];
$val=$_GET['val'];

//ค่ากำหนดของ ฐานข้อมูล
$dbhost = "localhost";
$dbuser = "";
$dbpass = "";
$dbname = "test";
mysql_pconnect($dbhost,$dbuser,$dbpass) or die ("Unable to connect to MySQL server");

if ($data=='province') {
echo "<select name='province' onChange=\"dochange('amper', this.value)\">\n";
echo "<option value='0'>==== เลือก สังกัด ====</option>\n";
$result=mysql_db_query($dbname,"select loc_code,loc_abbr from location where loc_name = location_name and loc_code != '000000' and flag_disaster is null order by loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='amper') {
echo "<select name='amper' onChange=\"dochange('tumbon', this.value)\">\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,2);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr ");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
} else if ($data=='tumbon') {
echo "<select name='tumbon' >\n";
echo "<option value='0'>======== เลือก ========</option>\n";
$val2=$val;
$val = substr($val,0,4);
$result=mysql_db_query($dbname,"SELECT loc_code, loc_abbr, loc_name, location_name FROM location WHERE loc_code != '000000' and loc_code != '$val2' AND loc_code LIKE '$val%' AND flag_disaster IS NULL ORDER BY loc_code, loc_abbr");
while(list($id, $name)=mysql_fetch_array($result)){
echo "<option value=\"$id\" >$name</option> \n" ;
}
}
echo "</select>\n";
?>




Download Source code :
ajax_dropdown.rar
mirror : ajax_dropdown.rar

( Please don’t directly link to the file… thank you )

PS. In ajax-dropdown.rar file Include
for states and cities (america)
state.php
state_dropdown.php
state.sql (MySQL)

for province ampher tumon (thailand)
locale.php
locale_dropdown.php
location.sql
(MySQL)

50 comments:

Peter said...

พี่ครับ

Peter said...

พี่ครับ ช่วยอธิบายเป็น Step By Step เป็นไทยด้วยได้ไหมอ่าครับ

คือแบบ งงมากๆอ่าครับ

ขอบคุณครับ

m2fu said...

Hi, I like this script a lot, but I am having trouble with doing my own variation of a drop down box system.

Basically I'm making a simple tire search system. You search what tires would be compatible with your car by selecting three linked drop down boxes which populate from a mysql database.

Can anyone help me out ?

superkeng said...

m2fu : you can see example tree linked drop down at "2. Select Province Ampher Tumbon to Show in Dropdown"

first box is " if ($data=='province')"
second box is " else if ($data=='amper') "
and last box is "else if ($data=='tumbon') "

$val is value send to sql query box2 and box3

peter : อยากให้อธิบายตรงไหน ถามมาเลยครับ

m2fu said...

Hi superkeng Can I email you because I need to explain a lot...
I can't get my third drop down box to populate

superkeng said...

mail to superkeng at gmail.com ^__^

bloodymental said...

hi.. great code... i jus have one problem.. i can get all the 3 drops down menus to populate however when i submist a form with a POST action it does not capture the value in the drop down.... any ideas?

Sheriff26 said...

Hi. This ajax dropdown is amazing!!
but I have a little problem with.
I use a phplib a templating system and if i use GET " req.open("GET", "?page=state&data="+src+"&val="+val);"
it include in the td the whole page :(
and if I specify it like this: " req.open("GET", "/state.php&data="+src+"&val="+val);"
don't work.

Any idea ?
Thanks

kaew said...

ถ้าเราต้องการ แสดงข้อมูลจากฐานเพื่อทำการแก้ไข
และใช้ ajax จังหวัด อำเภอ ตำบล เวลาโยนค่าทำอย่างไรช่วยอธิบายให้หน่อยนะคะ ตาม เมล์คะขอบคุณมา
boy1999@hotmail.com

kmustafa said...
This post has been removed by the author.
twin said...

สุดยอดมากเลยครับ เอาไปลองใช้แล้ว แต่เวลาเลือก อำเภอแล้วมีปัญหาครับ เพราะออกมาทั้งอำเภอและตำบล เมื่อเลือกจังหวัดหรือตำบลไม่มีปัญหาครับ ไม่รู้ว่าเป็นที่ ตารางหรือเปล่าครับ

อ้อ มี Email ไหมครับเพราะจะมีรายละเอียดที่จะเขียนถามยาวครับ (คือต้องอธิบายละเอียด)ครับ
ขอบคุณล่วงหน้า
inteltwin@gmail.com

Tooxic.com said...

Thank you for this... got it working in a few mins and was what I have been looking for for weeks.

matt said...

nice works, I will use that...

Phatrapol said...

รวมๆ แล้ว ก็ มาถูกทางแล้ว

อาจจะต้องแก้ไขอีกนิดหน่อย
ตรงส่วนโปรแกรม และส่วน database ที่ยังไม่สมบูรณ์ นัก

ตอนนี้ กำลังเรียงจังหวัดตามตัวอักษรอยู่
และ เพิ่มบางจังหวัดที่ตกหล่น
เช่น กระบี่ (ตอนนี้ กำลัง แก้ไขอยู่)

ยังไงก็ ขอบคุณ สำหรับ ตัวอย่างอันนี้

ก็ช่วยประหยัดเวลา ไม่ต้องทำเองไปเยอะมากเลย

ykpinar said...

Thanks for this. It is very useful but I having trouble also. I can not get the values when press submit button. I will be glad if anyone show the solution?

ykpinar said...
This post has been removed by the author.
Jason said...

Great tutorial and script - only problem I am having is when viewing the dropdown lists in IE - they slide all the way to the top of the screen - any suggestions?

g-O-r--a-g-o-d said...

โค้ดเต็มๆต้นฉบับ ตอนนี้เป็นแบบสมบูรณ์แล้ว ที่ http://www.goragod.com

ITyleR said...
This post has been removed by the author.
ITyleR said...

How is it possible to save selected the chosen value in a list (at the change of information of form)?

Wolverine said...

can you please explain how to implement this on blogger

glen said...

Tks for this. Been chasing around google for ages to find something that is simple and that works. Slick. Well done. Got it working with both dropdowns coming out of an Ingres database.

Heinz Wittenbecher said...

Thank you very much for this sampling of using dropdown with ajax. I've expanded it to 7, gathering information about a vehicle so that ultimately I can show a list of parts.

Where I'm a bit stuck is how to break out and go to a new page. I.e. I've collected all the info I need and now I want to go to a page where the resulting parts are displayed.

Thanks again and if anyone has some hints re breaking to a new page, thanks in advance.

jk said...

Hi,

This is a nice tutorial. But I have a problem.

When you select the category1 (firstdropdown) then the category2 list shows. But when you keep change in the category1 little faster for a while and stops, the sub category stops show the result and later it stops works totally. Why ajax gets stuck when this kind of events occurs?

Fes x said...

Hi,

Excellent script!

Can you show me how i can have the dropdowns pre loaded and options selected?

nikon said...

Thank you very much!
Great script!

Mike said...

Looks nice, but you can't download it. Anyone have it uploaded somewhere real people can download it? (I.E.: NOT those stupid, lame-assed, 'free' upload sites?)

omni said...

Hi, great script, but I'm trying to create a page where both dropdowns are defaulted on page loading from a mysql database.
Any hints on how to do this would be great. I can get the values from the database, just can't get the dropdowns to take on these values when page loads.

balicenter said...

Waw. its cool thank for sharing, and keep posting

regard'

Bali Villas

akos said...

Nice tutorial!

Pêle-Mêle said...

Hi Superkeng this is great. But I am having trouble understanding the difference between the first and second script...

Pêle-Mêle said...

I mean, do I have to use both codes ? or does one replace the other? the reason I an saying this is that when I run the first code, I get two drop downs and when I run the second one, I get another drop down.

akos said...

Hi!As you see, the first code creates two dropdown list, the second section dropdown will changes depending from the first list.(See the images.
----------------)
The second dropdons creates 3 dropdown lists. But the 2 codes in my opinion is a bit different. Hello,
akos

Pêle-Mêle said...

Akos, sounds like in the first code, there is no use of mysql database...am I correct?
I have a database that has state and city, I want the user to first select a state and then the list of corresponding cities will show up in the second drop down. which code am I suppose to use?

akos said...

on the dropdown image you will see:
mirror : ajax_dropdown.rar

You will find state_dropdown.php the Javascript(inside), and the original empty dropdowns.

But in state.php you have to change the database connection, that will make the changing dropdowns...

Run state.sql in phpmyadmin (run the SQL command.)

Hello!

paulo said...

hi, this doesnt work with me, it only appears this:

"; echo ""; $result=mysql_db_query($dbname,"select loc_code,loc_abbr from location where loc_name = location_name and loc_code != '000000' and flag_disaster is null order by loc_abbr"); while(list($id, $name)=mysql_fetch_array($result)){ echo "$name \n" ; } } else if ($data=='amper') { echo "

akos said...

This coderesult might comes if your server doesn't allow the short open php tags.

how to solve it? replace all < ? into < ? php

hello, jjozsi.

paulo said...

yes i have found some minutes ago, i was just reply when you reply. one stuff how the triple example database works? i know that the 2 dropdown works with 2 table, the triple example is working with one table and since he doesnt appear the data because its in Thai i cannot figured it out. Can you explain it please? Best Regards

akos said...

I did not tried the triple dropdown yet :) Becouse i modified it to pupolate a textarea using two dropdown list, for a project/table/ --> fieldnames lister.

I would help to comment the triple dropdown, but not today.

paulo said...

i found one problem. Its not working on Internet Explorer, do you know why? its working just fine on firefox.

the IE give this error: "document.getElementById(...) is null and its not an object"

regards

akos said...

i use this code snippet on Opera, Firefox, Internet explorer. go to http://www.phpbuilder.com/board/ and post that problem. i'm a member of that forum with lots of experts. They can help to you. i can only suggest this. Hello, akos

george said...

something similar for those AJAX inclined

http://imagecowboy.com/articles/create_ajax_menu_asp_part1.asp

phpcode.hu said...

Hy all :) i've chenged a little this code, to update database tables:

you can generate it here:
http://phpcode.hu/ajax_updater/

Brian said...

Hi,

The code works great! It's the 3rd script I try and it finally works.

I have 2 drop downs (country and region) and a button that when pressed is suppose to add a marker on my google map centered to the region. It worked before but now it does nothing.

I call this with my button: onClick="showAddress();"

And this is my function:

function showAddress() {
var countryID = document.getElementById("countries");
var country = countryID.options[countryID.selectedIndex].text;

......... (the rest of the code that creates the marker on the map)
}

When I use this in the function
alert(countryID);

I get this: [object HTMLFontElement]


What can use to access the region and country from the drop downs?

Thanks,
Brian

phpcode.hu said...

Hello there, i've made an ajax generator for table update, but now you can design sub dropdowns and textfields. Test it here:
http://phpcode.hu/teszt/ajax/

Video tutorial:
http://www.youtube.com/watch?v=h7AMMb4bVgY

Demo is here:
http://phpcode.hu/teszt/ajax/ajax_teszt_update.php

kit said...

May i know to predefine the state and city as selected? Example, when register user using your script is work fine. But when want to update account, i need to retrieve the stored value and set the state & city as selected. How do i do this? Please help. Thanks.

kit said...
This post has been removed by the author.
phpcode.hu said...

if you're using php, you can change the clint side output to re-call the dropdowns with the selected state and city numbers.

http://phpcode.hu/one_click_repo/?h=331bd2a1_99

kit said...

Thanks for quick reply. But the code not work for me and i've figure it out. Below is my code:

function dochange(src, val, selected) {
.
.
req.open("GET", "state.php?data="+src+"&val="+val+"&selected="+selected);
.
}

dochange('State', state_value, 0);
dochange('Area', state_value, area_value);

dochange should pass in state_value instead of area_value and need to pass selected value to php then only can set the selected area. :) Thank you.

phpcode.hu said...

Yes, the two values needed to embed into the javascript calls. In the original code body.onload reload the first dropdown with a value: -1

this is what you can make if you want to reload all the dropdowns.