[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

AJAX/PHP/MySQL Multiple Dropdowns

Posted on 2009-12-17
24
Medium Priority
?
885 Views
Last Modified: 2012-05-08
Hi

I am trying to create a script exactly like the drop-down boxes on http://saturnregina.autotrader.ca/index.htm. I tried to do it, but I wasn't able to link the first drop-down to 3,4,5 & 6 drop-downs and then, I don't know how to put a onChange Event on all other drop-downs so that the when they are changed other drop-downs are also updated from the database. If someone can help me with this, it will be greatly appreciated.

Thanks
0
Comment
Question by:theicon
  • 8
  • 6
  • 5
  • +3
22 Comments
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26077448
As far as your onchange event for each dropdown box that is simple.

<form>
<select name="main" onchange="this.form.submit()">
<option value=1>Option 1</option>
<option value=2>Option 2</option>
<option value=3>Option 3</option>
</select></form>

That will submit the form back to the same page so you can setup variables to find out what values have been selected.

but I would imagine you would need to setup a query based on the selected values. If you could supply more information as to how your table(s) are setup and what data there is in them I could offer more help.
0
 
LVL 5

Expert Comment

by:manomani
ID: 26077768
Hi buddy.,

Just try this

http://codestips.com/php-ajax-cascading-dropdown-using-mysql/

which works fine.. follow the instructions.
0
 
LVL 3

Expert Comment

by:jagdishshirsat
ID: 26078260
hi,

Here is the working example. Code download is also availalbe.

http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php

Thanks
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:theicon
ID: 26082394
Hi

I had already found scripts like these before. Check this - http://www.dhtmlgoodies.com/index.html?whichScript=ajax_chained_select

This is what I was using earlier. I could link only two drop-downs. In the link (http://saturnregina.autotrader.ca/index.htm), when you change year, all other drop-downs are also changed simultaneously. Or, if you change something else afterward or before, all drop-downs are updated accordingly. So, please help me according to that.

Thanks
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26084797
TheIcon:  I will write you up a code to do what you want. Just give me a little while as I'm trying to work at the same time.....
0
 

Author Comment

by:theicon
ID: 26084881
Thanks Elvin66. I'll be grateful to you if you could do it...
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26085961
Working on it now :)
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26085970
Actually, I can do a version which does not use ajax if that is ok with you. It will do the same job. I'm not that familier with running ajax although I know it is good. You could try taking my version and including ajax if you like.
0
 

Author Comment

by:theicon
ID: 26097812
If it does the same work then its ok with me.
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26099749
theicon:

I have tried 3 different ways of coding this and unfortunately have not been able to make it work!!! This is not a difficult thing to do but my way of thinking is off a little. I will continue to try and resolve this but I think you should click the "request attention" button at the top of this question so a moderator can send out an alert to other experts. They can also move it to different locations if more appropriate.

I hate it when something is beating me arggg... :)
0
 

Author Comment

by:theicon
ID: 26099807
Ok. Thanks for your attempt and the suggestion.
0
 
LVL 14

Accepted Solution

by:
profya earned 2000 total points
ID: 26103904
I wrote this example specially for your case. It uses ajax to fill combo boxes. The solution I am attaching contains the html file containing the form, a php file containing the code accessing the database and the sample database script and the jquery library.
the database name is: text.

I hope you find it useful.

profya.zip
profya.PNG
0
 
LVL 18

Expert Comment

by:Hube02
ID: 26104013
This is what I would do, or a description of how I would proceed with something like this.

First, all of the onchange events on all of the select elements would call the same JavaScript function.
When this function is called it would retrieve all the values from all of the select elements and then this function would make an AJAX request sending this information.

You would perform your DB query based on the information sent.

I would construct a multidimensional array from this data, for instance:

$return_array['year'] = array(YEAR => QUANTITY, YEAR => QUANTITY).
$return_array['make'] = array(list of makes here);
etc....

To return this array I would use JSON http://www.json.org/
JSON can be created by PHP by using:
$json = json_encode($return_array);

Now the data, in a JSON string is received by the requesting page and you would parse the JSON string in JavaScript and dynamically populate each of the select boxes, first you would clear anything that is in them and then you would loop through each of the array elements and insert a new optionfor each one returned.

You'll also need to remember which ones were already selected so that you can mark them as selected when you create each new option element in each list.

Hopefully this helps to get you organized in some way. this isn't really a simple question but a significant piece of work that needs to be accomplished. I also seriously doubt that you will find anything "Off the Self" that can do what you need done.
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26106933
I have managed to get it working but at this stage, only with two drop down /select boxes. I think that the ajax sollutions are going to be the best method after working on this. The queries to run all 6 selectboxes would be quite complicated using my method.
0
 

Author Comment

by:theicon
ID: 26109066
Thanks profya for the script. I am trying to use it and it isn't work in IE. It gives an error -

------------------------------------
Message: Object doesn't support this action
Line: 15
Char: 11
Code: 0
URI: http://****/profya.html
------------------------------------

However, it works fine in Firefox. If you can help me fix the error, then I can use this script. This is not exactly what I want but its a good start for me. If I won't be able to do exactly what I want to, then I'll just use this kind of script and keep it simple.

What's left? -

I am trying to figure out that how I can use the script (provided by profya), to make it run similar to http://saturnregina.autotrader.ca/index.htm. Here, if we select the make first and then the year, the rest of the fields are changed accordingly. However, if we select year and then make, its different. So, its sending some parameters which are used to specify some conditions with the query which is executed first. I'll update here I have any success.
0
 
LVL 14

Expert Comment

by:profya
ID: 26118651
I am checking it out now.
0
 
LVL 14

Expert Comment

by:profya
ID: 26118683
Replace profya.html with the code attached. I missed to declare item as:
var item=.......

It is now working on IE.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <script type="text/javascript" src="jquery-1.3.2.js"></script>
  <script type="text/javascript">
  try
  {
  $(document).ready(function()
  {
      $("#company").change(function(event)
      {
          var item=document.getElementById("company");
          if (item.selectedIndex!=-1)
          {
              id=item.options[item.selectedIndex].value;
              $.get("comboapi.php", {q:'model', id: id}, function(result)
              {
                  fillCombo("model", result);
                  $("#model").change();
              })
          }
        
      })      

      $("#model").change(function(event)
      {
          var item=document.getElementById("model");
          if (item && item.selectedIndex!=-1)
          {
              id=item.options[item.selectedIndex].value;
              $.get("comboapi.php", {q:'car', id: id}, function(result)
              {
                  fillCombo("car", result);
              })
          }
        
      })      

	  $.get("comboapi.php", {q:'company'}, function(result)
	  {
          fillCombo("company", result);
          $("#company").change();
	  })

  }
  )
  function fillCombo(id, values)
  {
      var combo=document.getElementById(id);
      combo.options.length=0;
      if (values.length>0)
          {
              var rows=values.split(",");
              combo.options.length=rows.length;
              for(i=0; i<rows.length; i++)
              {
                  row=rows[i].split("^");
                  combo.options[i].value=row[0];
                  combo.options[i].text=row[1];
              }
          }
            
  }
  }
  catch (e)
  {
	alert(e.message);
  }
  </script>

 </HEAD>

 <BODY>
 <FORM METHOD=POST ACTION="">
	<SELECT NAME="company" id="company" style="width:100px;">
		
	</SELECT>
	<SELECT NAME="model" id="model" style="width:100px;">
	</SELECT>
	<SELECT NAME="car" id="car" style="width:100px;">
	</SELECT>
  </FORM> 
 </BODY>
</HTML>

Open in new window

0
 
LVL 14

Assisted Solution

by:profya
profya earned 2000 total points
ID: 26118716
Try this attached code if you don't want default selections:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <script type="text/javascript" src="jquery-1.3.2.js"></script>
  <script type="text/javascript">
  try
  {
  $(document).ready(function()
  {
      $("#company").change(function(event)
      {
          var item=document.getElementById("company");
          if (item.selectedIndex!=-1)
          {
              id=item.options[item.selectedIndex].value;
              $.get("comboapi.php", {q:'model', id: id}, function(result)
              {
                  fillCombo("model", result);
                  $("#model").change();
				  document.getElementById("car").options.length=0;
              })
          }
        
      })      

      $("#model").change(function(event)
      {
          var item=document.getElementById("model");
          if (item && item.selectedIndex!=-1)
          {
              id=item.options[item.selectedIndex].value;
              $.get("comboapi.php", {q:'car', id: id}, function(result)
              {
                  fillCombo("car", result);
              })
          }
        
      })      

	  $.get("comboapi.php", {q:'company'}, function(result)
	  {
          fillCombo("company", result);
          $("#company").change();
	  })

  }
  )
  function fillCombo(id, values)
  {
      var combo=document.getElementById(id);
      combo.options.length=0;
      if (values.length>0)
          {
              var rows=values.split(",");
              combo.options.length=rows.length;
              for(i=0; i<rows.length; i++)
              {
                  row=rows[i].split("^");
                  combo.options[i].value=row[0];
                  combo.options[i].text=row[1];
              }
			  combo.options.selectedIndex=-1;
          }
            
  }
  }
  catch (e)
  {
	alert(e.message);
  }
  </script>

 </HEAD>

 <BODY>
 <FORM METHOD=POST ACTION="">
	<SELECT NAME="company" id="company" style="width:100px;">
		
	</SELECT>
	<SELECT NAME="model" id="model" style="width:100px;">
	</SELECT>
	<SELECT NAME="car" id="car" style="width:100px;">
	</SELECT>
  </FORM> 
 </BODY>
</HTML>

Open in new window

0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26120841
profya:  Would you please re-export your sample sql file from your 'test' database. I would like to test it out and play around with the code. The only table in your .sql file was "model" - no company etc....

Also, I have attached the code that I worked on to do what "theicon" was asking for, only I have only 2 select boxes at this stage - (Make and Model). Maybe you could suggest a way to add more. Your use of functions is much more efficient than my queries. If you could tidy it up, it might just work. Thanks. Oh and I have attached the sql file as well.
Vehicles.sql
index.php
results.php
0
 
LVL 14

Assisted Solution

by:profya
profya earned 2000 total points
ID: 26126644
I have attached you the sample database.
test.sql
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 26128682
Thanks profya !!
0
 
LVL 14

Expert Comment

by:profya
ID: 26129997
No thanks elvin66, you are welcome.
0

Featured Post

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
Recursive SQL is one of the most fascinating and powerful and yet dangerous feature offered in many modern databases today using a Common Table Expression (CTE) first introduced in the ANSI SQL 99 standard. The first implementations of CTE began ap…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses
Course of the Month18 days, 20 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question