Chained Select Boxes using PHP / MySQL / AJAX / jQuery

UPDATE

Well everyone, I’m almost done with the generator!!

Watch this short clip to see it in action.


If you are interested in this tool it is for sale, while I get together a payment system you can contact me about trying out a beta.

DEMO

2 and 3 Dropdowns available in the download.

tier

It is fairly simple and consists of only 3 files. An index, database connection and a function file. So lets start.

Make your database table and fields. you can use mine for now.

CREATE TABLE IF NOT EXISTS `two_drops` (
  `id` int(11) NOT NULL auto_increment,
  `tier_one` varchar(255) NOT NULL,
  `tier_two` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM ;

INSERT INTO `two_drops` (`id`, `tier_one`, `tier_two`) VALUES
(1, 'Colors', 'Red'),
(2, 'Colors', 'Blue'),
(3, 'Colors', 'Green'),
(4, 'Colors', 'Yellow'),
(5, 'Colors', 'Black'),
(6, 'Shapes', 'Square'),
(7, 'Shapes', 'Circle'),
(8, 'Shapes', 'Triangle'),
(9, 'Shapes', 'Rectangle'),
(10, 'Shapes', 'Oval');

Make your connection to your database. db.php

mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());

Next we will add the jQuery, loading, results and main form in index.php

add your includes at the top of the page.

  //include your database connection and function files.
  include('db.php');
  include('func.php');

and the rest of the page.

//jquery framework
$(document).ready(function() {
	$('#wait_1').hide();
	$('#drop_1').change(function(){
	  $('#wait_1').show();
	  $('#result_1').hide();
      $.get("func.php", {
		func: "drop_1",
		drop_var: $('#drop_1').val()
      }, function(response){
        $('#result_1').fadeOut();
        setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
      });
    	return false;
	});
});

function finishAjax(id, response) {
  $('#wait_1').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}

Ok, that was easy enough. Now for the functions func.php

//**************************************
//     Page load dropdown results     //
//**************************************
function getTierOne()
{
	$result = mysql_query("SELECT DISTINCT tier_one FROM two_drops")
	or die(mysql_error());

	  while($tier = mysql_fetch_array( $result )) 

		{
		   echo ''.$tier['tier_one'].'';
		}

}

//**************************************
//     First selection results     //
//**************************************
if($_GET['func'] == "drop_1" && isset($_GET['func'])) {
   drop_1($_GET['drop_var']);
}

function drop_1($drop_var)
{
    include_once('db.php');
	$result = mysql_query("SELECT * FROM two_drops WHERE tier_one='$drop_var'")
	or die(mysql_error());

	echo '


 ';
    echo '
';
}

And thats it. Download the files below.

DEMO

DOWNLOAD

Want more helpful and free scripts? Buy me a cup of coffee to keep me goin!

Click here to lend your support to: Chained Select Generator and make a donation at www.pledgie.com !

468 ad

184 Responses to “Chained Select Boxes using PHP / MySQL / AJAX / jQuery”

  1. Well I tried doing that , but I just can’t get it

    • which part is not working, can you post what you have done.

      • Hi Rob,

        try to implement it, but web page say:

        “Notice: Undefined index: func in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\RoomDiary\scripts\func.php on line 21″

        The offending line in func.php:

        if($_GET['func'] == “drop_1″ && isset($_GET['func'])) {
        drop_1($_GET['drop_var']);
        }

        I have to agree its not a function, just a bit of code.

        I run php version 5.3.4 on windows with an Apache server.

        • try this

          if($_GET['func'] == “drop_1″ && isset($_GET['func'])) {
          drop_1($_GET['drop_var']);
          }

          • I am also getting the same undefined index error. Rob, the alternative code you posted also gives the same error?? Is there any difference between the code, they look identical. Can you help me out. Thanks!

          • if($_GET['func'] == “drop_1″ && isset($_GET['func'])) {
            drop_1($_GET['drop_var']);
            }

            still doesn´t work in my opinion, it is exactly the same code as posted before.

            this one works with me:

            if (isset($_GET['func'])&& $_GET['func'] == ‘drop_1′ ) {
            drop_1($_GET['drop_var']);
            }

            i switched the $_GET['func'] == ‘drop_1′ ) and isset($_GET['func']so he would first check if ‘func’ isset

  2. Yes your right, I have them in the same table..

    so how do it now

    Roger

    • Change everything called category to artist and everything called text to album.

      in the form where you see this..

      is where the php goes, under the form snippet. that populates the form.

  3. WOW this is just what I was looking for….

    I have a table with `artist` and one with `album` how would I change this to show Artist in first and Album in the second,
    Really would appreciate any help that could be given.
    Note: I spent 2 hrs trying to solve this myself, without any luck…

  4. @Bryan

    2 tables, one is just categories the other is categories and the text for the seconds dropdown. its just matching categories.

  5. In regards to my last post, I’m having trouble populating the second select box once something was chosen from the first select box.

    About the db, are there various tables? How are the select boxes linked to each other inside the db?

    Regards,
    Bryan

    • I’m having trouble with the same thing. I get the first box to populate just fine. As soon as I select one of the options from the list, it seems to crash. It just sits at “Please Wait”. I’d love some help on this.

  6. Rob,

    How did you organize your db? I can’t seem to figure out tying my db with the code you have provided.

  7. Very cool, Rob. After I posted the question, I found out it could be done with the visibility: hidden style.

    Thanks

  8. How many child-trees can there be off of the parent?

    Is there a way to completely hide the select boxes that come after the first one? In the demo there are two select boxes but the second one has nothing in it. Would it be possible to make the select boxes appear as needed?

    Regards,
    Bryan

  9. This came in really handy and after some tweaking works perfectly for what I needed to do. Thanks for making this available…it saved me loads of time!

  10. Very cool, implemented this into a site I’m developing :) Had to make a few changes as my categories and sub-categories are stored in seperate tables in the DB.

    I’ve also set it to pre-select whatever category is currently being viewed, but having a little difficulty pre-selecting the sub-category. Gonna stick at it a while longer and will post up my code when working if anyone wants it.

    Thanks for the initial code, has certainly helped.

Trackbacks/Pingbacks

  1. chained dropdown lists with php and mysql « nawabpurwebs - [...] http://www.blueicestudios.com/chained-select-boxes-using-php-mysql-ajax/ [...]
  2. Invaluable Sites – Links « MMtech Final Major Project - [...] http://www.blueicestudios.com/chained-select-boxes-using-php-mysql-ajax/comment-page-2/#comments [...]
  3. Chained Select using PHP and SQL « Vale Studios - [...] to a specific URL based on their selection. Most of the credit for this script must go to Rob ...
  4. ajax chained select on main page issue |Prestashow.com - [...] The script is essentially http://www.blueicestudios.com/chaine…hp-mysql-ajax/ [...]

Leave a Reply