but how? ive already tried some AJAX examples and cant get any to work..
can you help me code one please?
Main Topics
Browse All Topicsany chance of getting this to work?
our senerio:
ive got 3 fields in a table called location, title and jobtype
i want to have 3 select boxes and have them dynamically populate based on the selectbox selections.
example 1:
if i select location = Aberdeen, then the titles selectbox will be populated with titles where location = Aberdeen
or if i select location = Dublin, then the titles selectbox will be populated with titles where location = Dublin...
exmaple 2:
if i select location = Aberdeen, I should get all titles where location = Aberdeen. then say i pick title = Programmer from that aberdeen title list, then the jobtypes selectbox will be populated with jobtypes where location = Aberdeen and title = Programmer...
remember these values are coming from a database table and not a predefined array...
can this be done and how?
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Hi ellandrd,
I wrote my first Ajax app after reading this tutorial.
Maybe it'll help you as well :)
http://rajshekhar.net/blog
- Maddog
>>yes, we want points from you but you'll keep comming again and againg if somebody gives you code for everything...
look in my profile...
i dont expect somebody to code a complete application for me...I can program myself, but each time ive tried to code this application, i cant get it working... i need to get help/advice from you if your willing to provide it...
There are four options (3rd option is what you wanted):
(1) Server-Side: If you need to get the data for the second drop down box data from the database then re-parse the page to the web server. (i.e.) You can use onchange="this.form.submit
(2) Client-Side: Query the database initially and store all results in a JS array. Then, you can use onchange="jsFunction()" in your first drop-down box, where jsFunction() is the JavaScript function that actually populates the second drop-down based on the selected value and the pre-defined JS array. Its better to do it on server side if your total count of option combinations is greater then two thousand combinations, because JavaScript function needs to have ALL data at browser side. Here's my previous similar question: http:Q_21103384.html Its infact very easier to generate JavaScript array based on Query result sets.
(3) JSRS: JavaScript Remote Scripting with which you dont need to worry about the number of combinations of options and page reloading. Here are the links:
http://www.ashleyit.com/rs
http://www.ashleyit.com/rs
(4) Frames: Have every selection box in a frame and populate based on the previous frame selection box values selections. But Frames is not a good solution comparing others.
The options are read remotely from the DB through Javascript. As stated, download the files and and modify select_rs.php (http://www.ashleyit.com/r
Here's yet another tutorial. This one is actually based on ASP, not PHP, but can be easily modified to PHP.
I wrote this tutorial, so I'd be happy to help you with any problems you have along the way.
http://www.applicationgrou
Hope this helps,
Neal.
Yes, the data come from a database. When you select an option from the first select box an AJAX call is made to determine what options are available for the second select box. When you select an option from the second selet box an AJAX call is made to determine what options are available for the third select box, and so forth.
The ASP part of the code in my sample is minimal and I can help you convert it to PHP. I'm by no means a PHP expert, but I can certainly get at least this going.
Neal.
ldbkutty
I have that demo working and but im not sure how to go about changing it to suit what i need?
it uses 3 tables...i only use 1: tblJobs and it is as follows:
job_id | location | title | jobtype
1 | ABZ | Programmer | contract
2 | ABZ | Engineer | Permanent
3 | LDN | Administrator | contract
can you help me?
Try with this select_rs.php:
<?php
require("jsrsServer.php.in
jsrsDispatch( "makeList modelList optionsList" );
function makeList () {
return serializeSql("select location, location from tblJobs order by location" );
}
function modelList ($loc) {
return serializeSql("select title, title from tblJobs where location='{$loc}' order by title");
}
function optionsList ($loc='', $title='') {
return serializeSql("select jobType, jobType from tblJobs where location='{$loc}' and title='{$title}' order by jobType");
}
function serializeSql( $sql ){
$link = mysql_connect("localhost",
mysql_select_db ("selectdemo");
$result = mysql_query ($sql);
$s = '';
while ($row = mysql_fetch_row($result)) {
$s .= join( $row, '~') . "|";
}
mysql_close($link);
return $s;
}
?>
and change the cbFillOptions function in select.php.js file to this:
function cbFillModel ( strModels ){
// callback for dependent listbox
window.status = '';
fillList( 'lstModel', strModels );
if(IDModel != noValue){
var params = [''+IDMake+'', ''+IDModel+''];
jsrsExecute( 'select_rs.php', cbFillOptions, 'optionsList', params);
}
}
The database used for my example is using an MS-Access database. Here is the structure
ID AutoNumber
Year Number
Make Text
Model Text
Engine Text
An example of the data is below.
ID Year Make Model Engine
29 2002 Mercury Mystique 4 Cylinder
30 2002 Mercury Grand Marquis 6 Cylinder
31 2002 Mercury Grand Marquis 8 Cylinder
32 2002 Lexus ES300 6 Cylinder
33 2002 Lexus GS300 6 Cylinder
34 2002 Lexus GS300 8 Cylinder
35 2002 Lexus SC300 4 Cylinder
Neal.
Dont seem to work:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>XMLHTTP Test</title>
<script>
function getHTTPObject() {
var req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest) {
try {req = new XMLHttpRequest();}
catch(e) {req = false;}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {req = new ActiveXObject("Msxml2.XMLH
catch(e) {
try {req = new ActiveXObject("Microsoft.X
catch(e) {req = false;}
}
}
return req;
}
function fill(sel) {
oHttp = getHTTPObject();
if (oHttp.readyState != 0) {oHttp.abort();}
var yr_sel = document.getElementById('y
var mk_sel = document.getElementById('m
var mod_sel = document.getElementById('m
var style_sel = document.getElementById('s
var sel_to_fill = document.getElementById(se
//clear all selects from the one we are filling on
//make the vars we need for the argument string
switch(sel){
case 'yr': yr_sel.options.length = 0;
case 'mk': mk_sel.options.length = 0;
case 'mod': mod_sel.options.length = 0;
case 'style': style_sel.options.length = 0;
}
var mod = ""
var mk = ""
var yr = ""
if (yr_sel.options.length > 0) yr = yr_sel.options[yr_sel.sele
if (mod_sel.options.length > 0) mod = mod_sel.options[mod_sel.se
if (mk_sel.options.length > 0) mk = mk_sel.options[mk_sel.sele
var sURL = "MultiDropDownXMLHttp2.asp
sURL += "?year=" + yr + "&make=" + mk + "&model=" + mod;
oHttp.open("get", sURL , true);
oHttp.onreadystatechange = function () {
if (oHttp.readyState == 4) {
var options = oHttp.responseText.split("
sel_to_fill.options[0] = new Option("Choose One:","");
for (i=1;i<=options.length;i++
sel_to_fill.options[i] = new Option(options[i-1],option
}
}
}
oHttp.send(null);
}
</script>
<style type=text/css>
.lbl {width:50px;float:left;}
</style>
</head>
<body>
<form method="post" name="frmCars">
<div class="lbl">Year:</div><se
<div class="lbl">Make:</div><se
<div class="lbl">Model:</div><s
<div class="lbl">Engine:</div><
<input type=submit />
<script>fill("yr")</script
</form>
</body>
</html>
<?php
/* ------------------ */
/* Create SQL Query */
/* ------------------ */
if (!isset($_GET["year"])) {
$sql = "Select distinct [year] From tblCars Order by Year";
}
elseif (!isset($_GET["make"])) {
$sql = "Select distinct Make From tblCars" .
" Where year = " . $_GET["year"] .
" Order by Make";
}
elseif (!isset($_GET["model"])) {
$sql = "Select distinct Model From tblCars" .
" Where year = " . $_GET["year"] .
" and make = '" . $_GET["make"] . "'" .
" Order by model";
}
else {
$sql = "Select distinct Engine From tblCars" .
" Where year = " . $_GET["year"] .
" and make = '" . $_GET["make"] . "'" .
" and model = '" .$_GET["model"] . "'" .
" Order by engine";
}
/* --------------- */
/* Open Database */
/* --------------- */
$db = new COM("ADODB.Connection");
$datapath= substr($_SERVER['SCRIPT_FI
$ConnStr = "Provider=Microsoft.Jet.OL
$db->open($ConnStr);
/* --------------- */
/* Get Records */
/* --------------- */
$rs = $db->execute($sql);
$output = "";
while (!$rs->EOF) {
if (!$output == "") $output = $output . ",";
$output = $output . $rs->fields[0];
$rs->movenext;
}
/* ----------------- */
/* Close Database */
/* ----------------- */
$rs->close;
$db->close;
/* ------------------ */
/* Display Output */
/* ------------------ */
echo $output
?>
im trying to run it on apache under:
W:\Apache\htdocs\sandpit\J
W:\Apache\htdocs\sandpit\J
in my URL i have: http://localhost/sandpit/J
also what would this be in PHP:
<%
' This section is just to display the results. Normally you
' would submit to another page, or have this page save the
' results to a database.
if request.form("yr") > "" then
response.write("<b>You Selected: </b><br />")
response.write("Year: " & request.form("yr") & "<br />")
response.write("Make: " & request.form("mk") & "<br />")
response.write("Model: " & request.form("mod") & "<br />")
response.write("Engine: " & request.form("style") & "<br />")
response.write("<input type=button value='Close Window' onclick='window.close();' />")
response.end
end if
%>
what do you get if you put in this for your URL:
http://localhost/sandpit/J
If you don't get any output be sure to check your PHP error log on your web server.
Neal.
in my logs i get this:
Fatal error: Uncaught exception 'com_exception' with message '<b>Source:</b> Microsoft JET Database Engine<br/><b>Description:
I though so - its my database...
see - this is a problem for me as i dont understand that way you connect to the access database.
i usually connect like this:
function db_connect()
{
$link_id = odbc_connect('MY_DSN_NAME'
return $link_id;
}
$link_id = db_connect();
$query = 'SELECT ....';
$result = odbc_exec($link_id, $query);
then i do either this:
while($row = odbc_fetch_array($result))
{
echo $row['MY_FIELD_NAME'];
}
or this:
$fieldname = odbc_result($results,'MY_F
.
Sorry but the way you coded the connecting is confusing me to what i already know....
anyways, we know the path the DB is wrong hence why my selectboxes are blank...
>> also what would this be in PHP:
Sorry I thought I had taken out all of the asp. I missed a spot though. As the note in it says this is not really important as it simply displays the results, normally you would be using php here to save the data or process it however you needed. I'll translate this below:
--------------------------
ASP Code
--------------------------
<%
' This section is just to display the results. Normally you
' would submit to another page, or have this page save the
' results to a database.
if request.form("yr") > "" then
response.write("<b>You Selected: </b><br />")
response.write("Year: " & request.form("yr") & "<br />")
response.write("Make: " & request.form("mk") & "<br />")
response.write("Model: " & request.form("mod") & "<br />")
response.write("Engine: " & request.form("style") & "<br />")
response.write("<input type=button value='Close Window' onclick='window.close();' />")
response.end
end if
%>
--------------------------
php code
--------------------------
<?php
/*
This section is just to display the results. Normally you
would submit to another page, or have this page save the
results to a database.
*/
if (! $_Post["yr"] == "") {
echo "<b>You Selected: </b><br />";
echo "Year: " . $_Post["yr"] . "<br />";
echo "Make: " . $_Post["mk"] . "<br />";
echo "Model: " . $_Post["mod"] . "<br />";
echo "Engine: " . $_Post["style"] . "<br />";
echo "<input type=button value='Close Window' onclick='window.close();' />";
die();
}
?>
--------------------------
I think the above code should work. I'm not too sure if the die() command is the same as response.end. Response.End in asp will stop the processing of the script at that point.
Neal.
ellandrd,
>> Sorry but the way you coded the connecting is confusing me to what i already know....
That's ok. As I stated earlier, PHP is not my primary langauge, so the way I am accessing the DB may be not the best way, or at least unusual by PHP standards.
If you have a DSN setup for your database and want to use that method, that is fine. I'll explain the code I've included in any case.
Here's the code I used for connecting to the database:
--------------------------
$db = new COM("ADODB.Connection");
$datapath= substr($_SERVER['SCRIPT_FI
$ConnStr = "Provider=Microsoft.Jet.OL
$db->open($ConnStr);
--------------------------
Let's look at it line by line
=====
$db - new COM("ADODB.Connection");
- This line creates an ADODB Connection. That means it creates a connection object. Calls to the db will be made through the connection object. This does not open the connection, it simply creates the object to hold the connection.
=====
$datapath= substr($_SERVER['SCRIPT_FI
- This is getting the path to the databse file. This is assuming that the mdb file is in the same path as the script that is calling it. (Not the safest way to go, but for demo puposes it will do). Here's how it breaks down. $_SERVER['SCRIPT_FILENAME]
W:\Apache\htdocs\sandpit\J
strrpos($_SERVER['SCRIPT_F
We use the substr() function to take all the characters up to the last backslash. This gives us in your case:
W:\Apache\htdocs\sandpit\J
Now we add "\db.mdb" to it and get the full path to the database file
W:\Apache\htdocs\sandpit\J
If you wanted to you could simply put in
$datapath = "W:\Apache\htdocs\sandpit\
This line simply makes the code more portable.
=====
$ConnStr = "Provider=Microsoft.Jet.OL
This simply creates a string that includes the type of database and the path to the data file. This will be used to open the connection in the next line.
=====
$db->open($ConnStr);
This actually opens the connection to the database. Now we have communications to the database and can run querys against it.
--------------------------
So lets say we want to get a recordset containing all of the records in the table tbCars. We could do it like this.
$sql = "Select * from tbCars";
$rs = $db->execute($sql);
This will create a recordset called $rs which we can use to view the data.
Hope this helps,
Neal
OK, Here's a working example with a zipped copy of the db and two php files.
http://www.applicationgrou
Neal.
ok ive just extracted the 3 files into:
w:\apache\sandpit\neal\
and tried to run:
http://localhost/sandpit/n
and the selectboxes are still blank?
do i have to enable something for AJAX or XMLHTTP to work? im using FF, IE6 and 7
I don't use apache, so I don't know if there is anything you need to do there. The fact that you were getting error messages in your php error log makes me think that things are probably set up ok.
is this correct? should it not be .php ?
Yes it should. I can't believe I didn't change that in my example after pointing it out above. I've corrected it in my example and the zip file. The line now reads:
var sURL = "MultiDropDownXMLHttp2.php
After fixing that I found another problem. The logic I was using to determine which drop-down needed to be filled in did not work in PHP. I have corrected this and updated the zip file on the tutorial. This can be found here:
http://www.applicationgrou
Sorry about the problems and frustrations this may have caused you
Neal.
ok ive just tried it on a windows server and it works perfect... i think it wasnt working for me as im using apache server and i thinking ADODB.Conncetion dont work on Apache... itsnt is just a ASP or IIS conection method??
Anyways, ive got it working on a Windows server, so now i going to change the connection method to use DSN.
When i have it working, i will post the code heres o you can add it to your website tutorial for users on Apache/Linux/Unix server...
ljubiccica
Yes but the way Neal connects is different to what i know:
http://www.experts-exchang
ellandrd,
I don't actually have that file any longer. The data code for this script was moved into the script itself and I guess I didn't update the "Show Source Code" page to reflect that. The code is exactly what has been posted above.
It is possible that my connection techniques do not work with Apache. Never having used Apache I don't know. As I stated earlier though, so long as you can get to the data it doesn't matter to the script how you make the connection. The Query Strings and general logic will remain the same.
Looking at your normal connection string you listed above:
--------------------------
function db_connect()
{
$link_id = odbc_connect('MY_DSN_NAME'
return $link_id;
}
$link_id = db_connect();
$query = 'SELECT ....';
$result = odbc_exec($link_id, $query);
then i do either this:
while($row = odbc_fetch_array($result))
{
echo $row['MY_FIELD_NAME'];
}
or this:
$fieldname = odbc_result($results,'MY_F
-------------------
You could run the code like this:
--------------------------
<?php
/* ------------------ */
/* Create SQL Query */
/* ------------------ */
if (empty($_GET["year"])) {
$sql = "Select distinct [year] From tbCars Order by Year";
}
elseif (empty($_GET["make"])) {
$sql = "Select distinct Make From tbCars" .
" Where year = " . $_GET["year"] .
" Order by Make";
}
elseif (empty($_GET["model"])) {
$sql = "Select distinct Model From tbCars" .
" Where year = " . $_GET["year"] .
" and make = '" . $_GET["make"] . "'" .
" Order by model";
}
else {
$sql = "Select distinct Engine From tbCars" .
" Where year = " . $_GET["year"] .
" and make = '" . $_GET["make"] . "'" .
" and model = '" .$_GET["model"] . "'" .
" Order by engine";
}
/* --------------- */
/* Open Database */
/* --------------- */
function db_connect()
{
$link_id = odbc_connect('MY_DSN_NAME'
return $link_id;
}
$link_id = db_connect();
then i do either this:
/* --------------- */
/* Get Records */
/* --------------- */
$result = odbc_exec($link_id, $sql);
$output = "";
while($row = odbc_fetch_array($result))
{
if (!$output == "") $output = $output . ",";
$output = $output . $row[0];
}
/* ------------------ */
/* Display Output */
/* ------------------ */
echo $output;
?>
I can't test this because I don't have Apache setup, but give it a try and let me know.
Neal.
OK, i have got my code working using your example.
since i was having issues with both versions, i managed to get it working after 2 days..
the code i managed to get working was this:
<?php
include('../includes/db.in
$link_id = db_connect();
if(empty($_GET["location"]
{
$query = "SELECT DISTINCT(location) FROM tblJobs";
$result = odbc_exec($link_id,$query)
$locations = array();
while($row = odbc_fetch_array($result))
{
$locations[] = $row['location'];
}
foreach ($locations as $location)
$parsedLocation .= $location.',';
$parsedLocation = substr($parsedLocation,0,-
echo $parsedLocation;
}
else if(empty($_GET["title"]))
{
$query = "SELECT DISTINCT(title) FROM tblJobs WHERE location = '".$_GET["location"]."'";
$result = odbc_exec($link_id,$query)
$titles = array();
while($row = odbc_fetch_array($result))
{
$titles[] = $row['title'];
}
foreach ($titles as $title)
$parsedTitle .= $title.',';
$parsedTitle = substr($parsedTitle,0,-1);
echo $parsedTitle;
}
else
{
$query = "SELECT DISTINCT(jobtype) FROM tblJobs WHERE location = '".$_GET["location"]."' AND title = '".$_GET["title"]."'";
$result = odbc_exec($link_id,$query)
$jobtypes = array();
while($row = odbc_fetch_array($result))
{
$jobtypes[] = $row['jobtype'];
}
foreach ($jobtypes as $jobtype)
$parsedJobType .= $jobtype.',';
$parsedJobType = substr($parsedJobType,0,-1
echo $parsedJobType;
}
?>
I know its long and reduntant but its the only code i could get working.. might be useful to rise this issue on your tutorials...
I will show you our live website using your dropdown example (credit/copyright going to Neal Schfer (nschfer)) later today....
thank you
p.s this is the notice i have in the page that ive used your code:
The Dynamic Filtering Select Boxes seen on this browse page is Copyright of Neal Schfer.
All credit going to Neal's hard work at developing such a tool. Learn more at http://www.applicationgrou
This is OK?
Business Accounts
Answer for Membership
by: ljubiccicaPosted on 2006-08-01 at 03:13:36ID: 17222314
that is exactly what AJAX does...
ki/AJAX
=)
http://en.wikipedia.org/wi
Hope it helps