Link to home
Start Free TrialLog in
Avatar of DanielR6
DanielR6Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Multiple Drop Down Boxes With AJAX and ASP

Hi EE,

I have an Ajax multiple dependent drop down box script that I'm trying to make some slight alterations to fit my purpose, but as I have limited knowledge of Ajax and a time limit I'm requiring a little assistance.

The URL to view it:
http://www.s133358835.websitehome.co.uk/dd1/ajax_dependent_dropdown.asp

The changes I need to make are as follows;

a) *The default options of each select box are manufacturer= "Choose Manufacturer", model= "Choose Manufacturer First". Can this be altered to manufacturer= Any Manufacturer, model= Any Model / Disabled until Selection Made.

b) As the select boxes have new default options of Any Manufacturer, Any Model, I need all database results to be displayed by default on page load.

c) Currently the results only update when making a selection from the model select box, could this be extended so that on changing the manufacturers that will also update the results.

An example to hopefully make things clear;

When the page first loads all database results are shown, and the select boxes show as described above*. With the disable function the user has to change the manufacturer before selecting a model. Until this is done the model select displays Any Model, when the manufacturer is selected Any Model becomes enabled. This will filter the page results to show all available models for that manufacturer. On selecting a particular model results will then filter down again. If the user then goes and selects "Any Manufacturer" again all results will be shown, and the model select will revert to displaying Any Model disabled.

Help on this would be gratefully received, if you require any further info let me know

Thanks in advance

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%
Response.Expires = 60
Response.Expiresabsolute = Now() - 1
Response.AddHeader "pragma","no-cache"
Response.AddHeader "cache-control","private"
Response.CacheControl = "no-cache"
 
sMan = -1
If Len(Request("sMan")) > 0 And IsNumeric(Request("sMan")) Then
	sMan = CInt(Request("sMan"))
End If
 
sMod = -1
If Len(Request("sMod")) > 0 And IsNumeric(Request("sMod")) Then
	sMod = CInt(Request("sMod"))
End If
 
Set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open Server.MapPath("cars.mdb")
 
If Request("method") = "ajax" Then
	Call getModels(sMan)
	conn.Close()
	Response.End()
End If
 
 
Sub getModels(manID)
	sql = "SELECT model.model_id, model.model_name"
	sql = sql & " FROM model INNER JOIN (manufacturer INNER JOIN man_mod ON manufacturer.manufacturer_id = man_mod.manufacturer_id) ON model.model_id = man_mod.model_id"
	sql = sql & " WHERE (((man_mod.manufacturer_id)=" & manID & "))"
	sql = sql & " ORDER BY model.model_name"
 
	Response.Write "<select name=""sMod"" onchange=""this.form.submit()"""
	If manID = -1 Then 
		Response.Write " disabled"
	End If
	Response.Write ">" & vbCRLF
	
	Response.Write "<option value=""-1"">Choose"
	If manID = -1 Then
		Response.Write " Manufacturer First"
	Else 
	Response.Write " Model"
	End If
	Response.Write "</option>" & vbCRLF
	
	If manID > 0 Then
		Set rsMod=Server.CreateObject("ADODB.recordset")
		
	
		rsMod.Open sql, conn
		While Not rsMod.EOF
			opt = "<option value=""" & rsMod("model_id") & """"
			If CStr(rsMod("model_id")) = CStr(sMod) Then
				opt = opt & " selected"
			End If
			opt = opt & ">" & rsMod("model_name") & "</option>" & vbCRLF
			Response.Write opt
			rsMod.MoveNext
		Wend
		rsMod.Close
	End If
	Response.Write "</select>" & vbCRLF
	Response.Write "<noscript><input type=""submit"" name=""GetModelsDetails"" value=""Get Model Details"""
	If manID = -1 Then 
		Response.Write " disabled"
	End If
	Response.Write "></noscript>"
End Sub
 
Sub getModelDetails(modID)
	sql = "SELECT model.model_id, model.model_name, manufacturer.manufacturer_name"
	sql = sql & " FROM model INNER JOIN (manufacturer INNER JOIN man_mod ON manufacturer.manufacturer_id = man_mod.manufacturer_id)"
	sql = sql & " ON model.model_id = man_mod.model_id"
	sql = sql & " WHERE (((model.model_id)=" & modID & "));"
 
	If modID > 0 Then
		Set rsModDetails=Server.CreateObject("ADODB.recordset")
		rsModDetails.Open sql, conn
		
		If Not rsModDetails.EOF Then
			Response.Write "<table border=""1"">" & vbCRLF
			Response.Write "<tr><td>model_id</td><td>model_name</td><td>manufacturer_name</td></tr>" & vbCRLF
			Response.Write "<tr><td>" & rsModDetails("model_id") & "</td>"
			Response.Write "<td>" & rsModDetails("model_name") & "</td>"
			Response.Write "<td>" & rsModDetails("manufacturer_name") & "</td></tr>" & vbCRLF
			Response.Write "</table>"
		End If
		rsModDetails.Close
	End If
End Sub
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>AJAX Dependent Dropdown</title>
<script type="text/javascript">
 
/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
 
var loadedobjects = "";
var rootdomain = "http://" + window.location.hostname;
 
function ajaxpage(url, containerid){
var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
		catch (e){}
		}
	}
	else
		return false
		
		page_request.onreadystatechange = function(){
		loadpage(page_request, containerid);
	}
 
	page_request.open('GET', url, true);
	page_request.send(null);
}
 
function loadpage(page_request, containerid){
	if(page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)){
		document.getElementById(containerid).innerHTML = page_request.responseText;
	}
}
 
/***Combo Menu Load Ajax snippet**/
function ajaxcombo(selectobjID, loadarea){
var selectobj = document.getElementById ? document.getElementById(selectobjID) : ""
	if(selectobj != "" && selectobj.options[selectobj.selectedIndex].value != ""){
		url = '<%=Request.ServerVariables("SCRIPT_NAME")%>?method=ajax&sMan=' + selectobj.options[selectobj.selectedIndex].value;
		ajaxpage(url, loadarea);
	}
}
</script>
</head>
 
<body>
<form name="form1" method="get" action="<%=Request.ServerVariables("SCRIPT_NAME")%>">
  <select name="sMan" id="sMan" onchange="ajaxcombo('sMan','content_model')">
  <option value="-1">Choose Manufacturer</option>
	<%
	Set rsMan=Server.CreateObject("ADODB.recordset")
	rsMan.Open "SELECT manufacturer_id, manufacturer_name FROM manufacturer", conn
		While Not rsMan.EOF
			opt = "<option value=""" & rsMan("manufacturer_id") & """"
			If CStr(rsMan("manufacturer_id")) = CStr(sMan) Then
				opt = opt & " selected"
			End If
			opt = opt & ">" & rsMan("manufacturer_name") & "</option>" & vbCRLF
			Response.Write opt
			rsMan.MoveNext
		Wend
	rsMan.Close
	%>
  </select>
  
  
  <span id="content_model"><%Call getModels(sMan)%></span>
  <input type="submit" name="GetModels" value="Get Models">
</form>
<%
If sMod > 0 Then 
	Call getModelDetails(sMod)
End If
conn.Close
%>
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Wayne Barron
Wayne Barron
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I am confused on "B & C"

Lets me see if I am confused enough here?

Are you saying that when you select [Manufacturer] that ALL results are shown?
If so.
Then yes it can be done, but I do not know AJAX, and this is the first time that I have
Ever looked at it, and it looks right promising, but I do not know how to do what you are wanting.

Maybe with some research, or someone else's assistance.

have a good one.
Carrzkiss
Avatar of DanielR6

ASKER

Hi carrzkiss

Thanks for your reply, I had just worked out how to change the the titles, it's the other bits that I'm mainly stuck on.

No it's when you select [ Any Manufacturer ], which is also the default setting that all results display.

Thanks for the input, if do find a solution lety me know as it's a little my level for re-writing, and I've posted the question twice and this is the first time i've had a response.

Dan
Can you please explain to me in detail exactly what you are trying to achive,
This way I will hopefully be able to better assist you on this.

It intrigues me for some reason.
So, All the details, information (Make up a little sample HTML File demostrating it)
Anything, just try to get as much information, but NOT to over whelming, and I will try to see what I can do.
As of right now, I am really not sure at to what you are needing/wanting to do.

Carrzkiss
Ok here goes;

This url shows what is currently going on;
http://www.s133358835.websitehome.co.uk/dd1/ajax_dependent_dropdown.asp

I have changed the select defaults to display 'Choose All Manufacturers' and 'Choose Models'.

What Im trying to achieve is;
1. When first loaded the page will display results of  'All Available Vehicles'.
2. If the user selects a Manufacturer this will do two things a) will filter the results currently showing to display 'All models under only that manufacturer'. b) will also change the Model select to have 'All models listed' (currently achieves this)
3. If the user then goes and selects a particular Model then this will further sort the results to display only that Model.
4. If the user then goes and selects 'Choose All Manufacturers' from the Manufacturer select, 'All Available Vehicles' will display once again.

I put a simple html page together to show this here;
http://www.s133358835.websitehome.co.uk/dd1/example.html

If it's possible Im also trying to alter the SQL so as to pull the required data from one table instead of two, to populate the select drop downs, as it's doing currently. Ive iincluded a sample of my database, and the table is named 'stock', on the off chance that you know a way.

Hope this explains things better!
Cheers
Dan





cars.mdb
and you did like me and made a demo to show exactly what you wanted.
And I thought that I was the only one that did that here.

I fully understand what it is that you are wanting.
I will look into it and see what I might be able to do.
If I cannot, and pretty sure, (I think) that there is someone else that might be able
To assist in here as well.

Have a good one.
Carrzkiss
Thanks Carrzkiss for taking the time to have a look, Im doing what I can to have a play around with it to see if I can make some progress, but Im sure your more likely to get better results.

Dan
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks for that, I don't mean to be ungrateful for the help and  I may be wrong but isn't this going backwards on what I already have. It does pull the results from a single database which is good, though it seems to contain similar scripting to the previous without the added functionality. Im very new to this so I could be well off mark, if so could you explain the reasoning for it, or how it differs.

Cheers
Dan
I am new to "AJAX" as well.
It is not something that I know that much about.
So, I found the information to be useful to learning how to work with AJAX and ASP.
It is a step back, but it is also a learning process, and it seems that it is a learning process
For the both of us.
And seeing that no one else is coming in to help in this issue, this is about how it is going to go.

I have to finish up a project right quick, and once I do that, I will look back into this case, and see if I can come up with anything that may prove to be a better chance of getting this done.

have a good one.
Carrzkiss
I have also just noticed this which seems strange;

URL: http://www.troikaleasing.co.uk/drop/Drop.asp

When you select a company a second drop down box appears but doesn't show in the source, and also the contents of the table that is written out does not display in the source code, would that mean that it wouln't be picked up by spiders?

Here's what Im using, i have started on some changes to the sql/conn but nothing major.
<%
Response.Expires = 60
Response.Expiresabsolute = Now() - 1
Response.AddHeader "pragma","no-cache"
Response.AddHeader "cache-control","private"
Response.CacheControl = "no-cache"
%>
<%
Set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open Server.MapPath("Northwind_testv1.mdb")
%>
 
<html>
<head>
<script src="selectcustomer.js"></script>
</head><body>
<form> 
Select a Customer:
<select name="customers" onChange="showCustomer(this.value)">
  	<%
	Set rsMan=Server.CreateObject("ADODB.recordset")
	rsMan.Open "SELECT CustomerID, CompanyName FROM Customers", conn
		While Not rsMan.EOF
			opt = "<option value=""" & rsMan("CustomerID") & """"
			If CStr(rsMan("CustomerID")) = CStr(sMan) Then
				opt = opt & " selected"
			End If
			opt = opt & ">" & rsMan("CompanyName") & "</option>" & vbCRLF
			Response.Write opt
			rsMan.MoveNext
		Wend
	rsMan.Close
	%>
  </select>
  
</form>
<p>
<div id="txtHint"><b>Customer info will be listed here.</b></div>
</p>
<%
	Set rsCustomerTbl=Server.CreateObject("ADODB.recordset")
	rsCustomerTbl.Open "SELECT * FROM Customers WHERE CustomerID= "& "'" & request.querystring("q") & "'", conn
 
     response.write("<table>")
do until rsCustomerTbl.EOF
  for each x in rsCustomerTbl.Fields
    response.write("<tr><td><b>" & x.name & "</b></td>")
    response.write("<td>" & x.value & "</td></tr>")
  next
  rsCustomerTbl.MoveNext
loop
 
response.write("</table>")
%>
</body>
</html>

Open in new window

OK.
I am going to try back on this one again.
I have finished up all the other project(s) from EE, so, I am going to try to help you get this thing going.

Will hopefully have something going here in a few. (I Hope)
Cheers for your input on this carrzkiss, Im still plodding along trying to get my head around it. Getting this to work as I need it has been a complete headache, although like you said it's a learning curve.
It is being a pain.
I have been looking into other ways of doing this as well, and have not had no luck.
I spent several hours on it Friday evening trying to get it to work with the other
Example, but cannot seem to make the 2 ends meet properly.

Maybe this week sometime will prove to be possitive, and one of us hopefully will be able to get it to working.

I do not give up, so, I will not give up on helping you to get this to work.
Let me ask you this?
If I find another way to do this, without the AJAX will that work? Or do you want it to use AJAX?
Cause I think that AJAX is the only one that will display the data without refreshing the page.
(or) Changing the URL, so I will have to really look deep into some old code, and see what I can come up with.

We will find a way to get this to work for your site.

have a good one.
Going to take a nap for about an hour or so, that is usually when I come up with my killer idea's.
Carrzkiss
DanielR6,
I notice the sample DB.  Is the code for the main html page here?  If not can you post it or a simplified version that would work with the DB and what you are asking.  Is the ASP code that works with the DB and sends the results to the AJAX script here too?  If not please provide it too.  It seems you have both but it isn't real clear which is which in the snippets above.  I will get the DB and the code in the original snippet to see if that is enough but I am concerned the original code may not be up to date or best to use for a quick, sample version of this.
bol
Please view
http:Q_24138184.html?cid=238#a23649946  (I hope I did that right)
There you will find the Database to download.
The source code is in his Main Post.
Download the db, and the source code, and run it.

If you can help him in this, please do so.
As I am very lost in trying to get this going for him, I have tried everything and I am out of it.
I do not know where else to turn on this one.
Thanks Carrzkiss!  Thanks for confirming the code to get.  I did see that DB file and have it.  The link looked good but you can simplify it more by doing just like ...
http:#a23649946
Basically type the   http : # a     part (spaces added so EE won't make a link with it) and then copy the ID of the comment after the letter a.
The method the code uses is unusual to me.  I have usually made something like this with a couple of pages and am use to "my" ajax script.  At first I didn't think this would work but I might be wrong.  It might've made things a little more complicated though to adapt to what the we need to do here (sort of seems to be built around this one use).  I am going to try to work with what we have here but an example of using AJAX and ASP with different files is at http:/Q_24008150.html .  I just mention this in case there is interest in an example.  It isn't meant as an answer for this.
bol
I have made some progress.  How important is it for this page to work if Javascript is disabled?  It will require a lot more work and will need to redo the whole thing I think.  Even then I don't know if it will work well.  What you want to do is dynamic?  No script would mean none of this new stuff and so basically a different page.
Am I right that the details table will always show?
What about the Make select when no manufacturer is selected?  Seems useless to have used and it might need to handled in another question but since it isn't disabled in theory it could be selected before the Manufacturer and the page won't really handle that well.
I am basically stuck working on showing the table.  The Model select just needed a little modification to your code but having the AJAX script return more than one thing (the Model and Details) means a more complicated script and page.  This can be done but will be like the question I pointed to above (using JSON and script to fill the fields).
bol
Good Evening (Or Morning in my case)
Dan will be checking in, at about 7:00am EST

Have a good one, going to get myself some sleep now.
Writing a book, and it is taking up a lot of spare time, so now it is sleep time.

have a good one, and I hope that you can get this one done for Dan.

Wayne
What would your suggestion be regarding being compliant with non-javascript? Currently if im correct this script will work if javascript is disabled. Were some changes to that needed in order to display the database table permanently.

Yes the goal im trying to achieve is that the details table would always be showing, and would update as the user makes their choice. If there was no manufacturer selected then the model select would display 'Any Model' as the manufactuer select would display 'Any Manufacturer', and the details table would be displaying all records. The user can't alter the model select from displaying 'Any Model', untill they make a selection from the  manufacturer. Then once they do that as an example, if they choose 'Audi' then the model select would display all available Audi models, and the details table would filter automatically to show  'All Audi Models', then filter down again if they were then to select a particular model.

In both your opinions is having this details table update dynamicaly when a select box is changed a wise choice? I was wondering about the performance side of things. As this details table is just an example, i will be adding more content and a thumbnail. Would I need to limit the number of records showing.

This may well be for another question, but what would your suggestion be, currently the 'Manufacturer',  'Model',  'Deriative' and all in the same table in my database where as the example from this page uses two and a joining table. ( I've added db with an example table called 'stock' ) Is this the correct way? I've tried to alter the SQL in order to read from this example as it more ressembles my real project.

As always bol, wayne your help in this is much appreciated
Dan
cars.mdb
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> If there was no manufacturer selected then the model select would display 'Any Model' <<

Yes that was what I was meaning, that there would be just the 1 choice. A list of models would only be available if the user made a selection from the manufacturers. ( I hope that wasn't something you already worked on.. if so I apoligise for not being concise enough)

As an expert I value your opinion, having the table dynamically update is probably more for asthetics rather having  a solid purpose, with that in mind if it was left so that it only updated with an onclick event, that would allow this script to be used if javascript was turned off ( would i be correct in saying so?)

>>I am not sure what the new MDB file is for or meant to show<<

One major issue among others was that the way that these select boxes are populated. The data comes from two individual tables which have a joining table to link the models to the manufactuers. The database i included has just the one table ( named 'Stock') with three fields that I wanted to use to populate three boxes rather than just the two shown here ie. Manufacturers, Models and Deriatives. This table  is similar to my vehicle database at present, but only including whats needed for the select boxes. Is it possible to to have three boxes that would populate from the single table laid out as it is, or do I need to create three individual tables one for Manufacturer, Model  and Deriative using an ID and Name for each to link them? If there is a more efficent way to store these vehicles, i would be happy to make any alterations that would help in this question.

Hope this has helped in trying to explain where Im going with this, bol thanks for being patient with me.

Dan
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi bol,
Im only guessing that the ajax isn't required now if the table isn't dynamically updated onchange. I think then it would more usefull to be able to use the script with JS turned off. Correct me if im wrong but as i was looking for all data to be displayed on page load it would be simpler to remove the ajax and just use JS to control the select boxes, and control the details table as i would normally. So it's the issue with select boxes that im having.

With regards to the database i may have worded it wrong, im not looking to change the database design, it's how the select boxes are populated from it. At present they take info from seperate tables, im trying to get them to read from the one as the only data i need to populate them with is Manufacturer, Model, Deriative. The DB that i uploaded was just a simple example of one table with those three fields and example data, in the hope that you'd have a better idea how to change the sql in the script, and add a third select box which is the deriative and the database that is currently used doesn't have that option.

I hope this makes things a little clearer.
Thanks Dan




Just as an example this site uses three ddl's, only difference being my thrid one is deriative, ie. 1.8 lx, 2.0 tdci etc not bodytype, you probably got the jist of what im asking, but i thought i mention it. they show how two of them are disabled untill a previous selection is made, although the disabled options for this would show 'all' instead of being blank.

http://www.carquake.co.uk/
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>I am not sure why you need to change the DB though.  The SQL query would be different but it seems basically the 3rd select has the same results as what you show in the detail table<<

The third select box doesn't have the same results as the details table at present, because it doesn't include details of the deriative, it only includes make and model, in two seperate tables! which is the reason for posting the new mdb where i did a mock table which has the make, model, deriative in the one. The reasoning behind is that I only want the user to be able to select from whats available in the database. Can this script be altered to include a third drop down?

If im not using the dynamic update on the table when the select boxes change, how would i go about removing the onchange event, as currently when i make a change the script just falls apart. Im guessing I dont need this line anymore

202: Call getModelDetails(sMod)

But would replace it with a details table that updates after the user has made their choices in the select boxes and clicked a button.

if you feel that im making this more awkward than necessay, let me know
Dan
Dan,
What is the status of this now?  I am sorry I was not able to respond already to your recent question on this.  I don't know if you have already been able to answer it with what we discussed earlier and answered.  If not please clarify how I can help with the last of this to answer your question here.  If this has moved on to a new, related issue then feel free to open a new question for it and post a comment here to let me know.  Hopefully the project is coming well.
bol
Hi bol, sorry its been so long, should have cleared this up sometime ago. The project is coming on well, though due to work commitments it doesnt get as much attention as it should, but thanks for asking.  Im not sure how to dish the points out on this, so if there is an objection i apoligise now.

Thanks both of you for your assitance. Dan