Dynamic Car Make, Model, Year, Battery dropdown form

Hello,

I did a tutorial on a website to make a chained dropdown and I almost finished it…

This is my index.php:

<?php
  include('db.php');
  include('func.php');
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chained Select Boxes using PHP, MySQL and jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">
$(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;
	});
	$('#wait_2').hide();
	$('#drop_2').change(function(){
	  $('#wait_2').show();
	  $('#result_2').hide();
      $.get("func.php", {
		func: "drop_2",
		drop_var: $('#drop_2').val()
      }, function(response){
        $('#result_2').fadeOut();
        setTimeout("finishAjax2('result_2', '"+escape(response)+"')", 400);
      });
    	return false;
	});
});

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

function finishAjax_tier_three(id, response) {
  $('#wait_2').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}
function finishAjax_tier_four(id, response) {
  $('#wait_3').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}
</script>
</head>

<body>
<p>
<form action="" method="post">

    <select name="drop_1" id="drop_1">

      <option value="" selected="selected" disabled="disabled">Selecteer Merk</option>

      <?php getTierOne(); ?>

    </select>

    <span id="wait_1" style="display: none;">
    <img alt="Please Wait" src="ajax-loader.gif"/>
    </span>
    <span id="result_1" style="display: none;"></span>
    <span id="wait_2" style="display: none;">
    <img alt="Please Wait" src="ajax-loader.gif"/>
    </span>
    <span id="result_2" style="display: none;"></span>
	<span id="wait_3" style="display: none;">
    <img alt="Please Wait" src="ajax-loader.gif"/>
    </span>
    <span id="result_3" style="display: none;"></span>

</form>
</p>
<p>
<?php if(isset($_POST['submit'])){
	$drop = $_POST['drop_1'];
	$drop_2 = $_POST['drop_2'];
	$drop_3 = $_POST['drop_3'];
	$drop_4 = $_POST['drop_4'];
	echo "U heeft een ";
	echo $drop." ".$drop_2." geselecteerd uit ".$drop_3." en u heeft daar deze accu voor nodig ".$drop_4;
}
?>
</body>
</html>

And this is my func.php

<?php
//**************************************
//     Page load dropdown results     //
//**************************************
function getTierOne()
{
	$result = mysql_query("SELECT DISTINCT make FROM vehicles ORDER BY make ASC")
	or die(mysql_error());

	  while($tier = mysql_fetch_array( $result ))

		{
		   echo '<option value="'.$tier['make'].'">'.$tier['make'].'</option>';
		}

}

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

function drop_1($drop_var)
{
    include_once('db.php');
	$result = mysql_query("SELECT DISTINCT model FROM vehicles WHERE make='$drop_var' ORDER BY model")
	or die(mysql_error());
	
	echo '<select name="drop_2" id="drop_2">
	      <option value=" " disabled="disabled" selected="selected">Selecteer Model</option>';

		   while($drop_2 = mysql_fetch_array( $result ))
			{
			  echo '<option value="'.$drop_2['model'].'">'.$drop_2['model'].'</option>';
			}
	
	echo '</select>';
	echo "<script type=\\"text/javascript\\">
$('#wait_2').hide();
	$('#drop_2').change(function(){
	  $('#wait_2').show();
	  $('#result_2').hide();
      $.get(\\"func.php\\", {
		func: \\"drop_2\\",
		drop_var: $('#drop_2').val()
      }, function(response){
        $('#result_2').fadeOut();
        setTimeout(\\"finishAjax_tier_three('result_2', '\\"+escape(response)+\\"')\\", 400);
      });
    	return false;
	});
</script>";
}

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

function drop_2($drop_var2)
{
    include_once('db.php');
	$result = mysql_query("SELECT DISTINCT year FROM vehicles WHERE model='$drop_var2'")
	or die(mysql_error());
	
	echo '<select name="drop_3" id="drop_3">
	      <option value=" " disabled="disabled" selected="selected">Selecteer Jaar</option>';

		   while($drop_3 = mysql_fetch_array( $result ))
			{
			  echo '<option value="'.$drop_3['year'].'">'.$drop_3['year'].'</option>';
			}
	
	echo '</select>';
	echo "<script type=\\"text/javascript\\">
$('#wait_3').hide();
	$('#drop_3').change(function(){
	  $('#wait_3').show();
	  $('#result_3').hide();
      $.get(\\"func.php\\", {
		func: \\"drop_3\\",
		drop_var: $('#drop_3').val()
      }, function(response){
        $('#result_3').fadeOut();
        setTimeout(\\"finishAjax_tier_four('result_3', '\\"+escape(response)+\\"')\\", 400);
      });
    	return false;
	});
</script>";
}

//**************************************
//     Second selection results     //
//**************************************
if(isset($_GET['func'])&& $_GET['func'] == "drop_3" ) {
drop_3($_GET['drop_var']);
}
function drop_3($drop_var3)
{
    include_once('db.php');
		$result = mysql_query("SELECT * FROM vehicles WHERE year='$drop_var3'")
	or die(mysql_error());
	
	echo '<select name="drop_4" id="drop_4">
	      <option value="" disabled="disabled" selected="selected">Selecteer Accu</option>';


		   while($drop_4 = mysql_fetch_array( $result ))
				{
				if ($drop_4['accu'] != "") {
			  echo '<option value="'.$drop_4['accu'].'">'.$drop_4['accu'].'</option>';
				}
  }
	echo '</select> ';
    echo '<input type="submit" name="submit" value="Submit" />';
}

?>

I have a database vehicles with “id”, “make”, “model”, “year” and “accu”

It is working correct but in the last dropdown “accu” it is showing all the accu’s from the selected “year” and I want only one accu that matches the other selections… for example

Volvo - XC90 - 2013 - and the accu belong to all fields…

How do I have to change my last function to make that work?

I allready tried this but that did not work:

function drop_3($drop_var, $drop_var2, $drop_var3)
{
    include_once('db.php');
        $result = mysql_query("SELECT * FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3'")
    or die(mysql_error());  

Can somebody help me out?:slight_smile:

Thanks in advance

So… where in your javascript up there do you send “drop_3” as the func?

EDIT: Okay, i think i see where it’s getting that from… but you arnt sending the additional variables to make the choices. You’re getting the wrong values for Year as well, but you havent noticed it :wink:

Thanks for the fast reply:)

I’m not that good with PHP that is why I did that tutorial… but you are saying the way I tried is not the right way? How should I do it then?

Well you’re not far off - you just need to modify the javascript echo in func.php to send the additional variables.


    echo "<script type=\\"text/javascript\\"> 
$('#wait_2').hide(); 
    $('#drop_2').change(function(){ 
      $('#wait_2').show(); 
      $('#result_2').hide(); 
      $.get(\\"func.php\\", { 
        func: \\"drop_2\\", 
[B]        drop_var: $('#drop_2').val() [/B]
      }, function(response){ 
        $('#result_2').fadeOut(); 
        setTimeout(\\"finishAjax_tier_three('result_2', '\\"+escape(response)+\\"')\\", 400); 
      }); 
        return false; 
    }); 
</script>"

Add additional variables for the ones you want to send; for your year selector, you want to send 2 variables (Make and Model), for your ‘accu’ selector, you want to send 3 variables (Make, Model, Year)

So my func.php file is allright but I dont send variable to the next dropdown? Is that what you are saying?

Your func.php needs to send more variables via javascript to your page functions. Currently it only sends two; func and drop_var (See the bold line in my last post, + the line before it.) You need to make it send more - func, drop_var, and drop_var2 (or whatever you want to call it) for the second dropdown selection, and func,drop_var,drop_var2,and drop_var3 for the third dropdown selection. That way your PHP can make a query based on ALL the information. (Which is what you tried to do in the second code block you posted. The right idea! just needed a little extra data.)

Ok,

I tried this:

<?php
//**************************************
//     Page load dropdown results     //
//**************************************
function getTierOne()
{
	$result = mysql_query("SELECT DISTINCT make FROM vehicles ORDER BY make ASC")
	or die(mysql_error());

	  while($tier = mysql_fetch_array( $result ))

		{
		   echo '<option value="'.$tier['make'].'">'.$tier['make'].'</option>';
		}

}

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

function drop_1($drop_var)
{
    include_once('db.php');
	$result = mysql_query("SELECT DISTINCT model FROM vehicles WHERE make='$drop_var' ORDER BY model")
	or die(mysql_error());
	
	echo '<select name="drop_2" id="drop_2">
	      <option value=" " disabled="disabled" selected="selected">Selecteer Model</option>';

		   while($drop_2 = mysql_fetch_array( $result ))
			{
			  echo '<option value="'.$drop_2['model'].'">'.$drop_2['model'].'</option>';
			}
	
	echo '</select>';
	echo "<script type=\\"text/javascript\\">
$('#wait_2').hide();
	$('#drop_2').change(function(){
	  $('#wait_2').show();
	  $('#result_2').hide();
      $.get(\\"func.php\\", {
		func: \\"drop_2\\",
		drop_var: $('#drop_1').val()
		drop_var2: $('#drop_2').val()
      }, function(response){
        $('#result_2').fadeOut();
        setTimeout(\\"finishAjax_tier_three('result_2', '\\"+escape(response)+\\"')\\", 400);
      });
    	return false;
	});
</script>";
}

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

function drop_2($drop_var2)
{
    include_once('db.php');
	$result = mysql_query("SELECT DISTINCT year FROM vehicles WHERE model='$drop_var2'")
	or die(mysql_error());
	
	echo '<select name="drop_3" id="drop_3">
	      <option value=" " disabled="disabled" selected="selected">Selecteer Jaar</option>';

		   while($drop_3 = mysql_fetch_array( $result ))
			{
			  echo '<option value="'.$drop_3['year'].'">'.$drop_3['year'].'</option>';
			}
	
	echo '</select>';
	echo "<script type=\\"text/javascript\\">
$('#wait_3').hide();
	$('#drop_3').change(function(){
	  $('#wait_3').show();
	  $('#result_3').hide();
      $.get(\\"func.php\\", {
		func: \\"drop_3\\",
		drop_var: $('#drop_1').val()
		drop_var2: $('#drop_2').val()
		drop_var3: $('#drop_3').val()
      }, function(response){
        $('#result_3').fadeOut();
        setTimeout(\\"finishAjax_tier_four('result_3', '\\"+escape(response)+\\"')\\", 400);
      });
    	return false;
	});
</script>";
}

//**************************************
//     Second selection results     //
//**************************************
if(isset($_GET['func'])&& $_GET['func'] == "drop_3" ) {
drop_3($_GET['drop_var']);
}
function drop_3($drop_var, $drop_var2, $drop_var3)
{
    include_once('db.php');
        $result = mysql_query("SELECT * FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3'")
    or die(mysql_error());
	
	echo '<select name="drop_4" id="drop_4">
	      <option value="" disabled="disabled" selected="selected">Selecteer Accu</option>';


		   while($drop_4 = mysql_fetch_array( $result ))
				{
				if ($drop_4['accu'] != "") {
			  echo '<option value="'.$drop_4['accu'].'">'.$drop_4['accu'].'</option>';
				}
  }
	echo '</select> ';
    echo '<input type="submit" name="submit" value="Submit" />';
}

?>

But after making a selection in the second dropdown it is stuck:( Am I doing it the wrong way?

your variables are being declared as an array, but you missed a seperator.


        func: \\"drop_2\\",    <--- NOTE THE COMMA.
        drop_var: $('#drop_1').val()  <----- NOTE THE LACK OF COMMA.
        drop_var2: $('#drop_2').val() 

You also need to pass the variables into the function calls…


if(isset($_GET['func'])&& $_GET['func'] == "drop_3" ) { 
drop_3($_GET['drop_var']);  /// needs to send $_GET['drop_var2'] and $_GET['drop_var3'] ....
}

You’re on the right track, just narrowing out those little bugs :wink:

You made my day!

I got it working now:) :

<?php
//**************************************
//     Page load dropdown results     //
//**************************************
function getTierOne()
{
	$result = mysql_query("SELECT DISTINCT make FROM vehicles ORDER BY make ASC")
	or die(mysql_error());

	  while($tier = mysql_fetch_array( $result ))

		{
		   echo '<option value="'.$tier['make'].'">'.$tier['make'].'</option>';
		}

}

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

function drop_1($drop_var)
{
    include_once('db.php');
	$result = mysql_query("SELECT DISTINCT model FROM vehicles WHERE make='$drop_var' ORDER BY model")
	or die(mysql_error());
	
	echo '<select name="drop_2" id="drop_2">
	      <option value=" " disabled="disabled" selected="selected">Selecteer Model</option>';

		   while($drop_2 = mysql_fetch_array( $result ))
			{
			  echo '<option value="'.$drop_2['model'].'">'.$drop_2['model'].'</option>';
			}
	
	echo '</select>';
	echo "<script type=\\"text/javascript\\">
$('#wait_2').hide();
	$('#drop_2').change(function(){
	  $('#wait_2').show();
	  $('#result_2').hide();
      $.get(\\"func.php\\", {
		func: \\"drop_2\\",
		drop_var: $('#drop_1').val(),
		drop_var2: $('#drop_2').val()
      }, function(response){
        $('#result_2').fadeOut();
        setTimeout(\\"finishAjax_tier_three('result_2', '\\"+escape(response)+\\"')\\", 400);
      });
    	return false;
	});
</script>";
}

//**************************************
//     Second selection results     //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_2" ) {
drop_2($_GET['drop_var'], $_GET['drop_var2']);
}

function drop_2($drop_var, $drop_var2)
{
    include_once('db.php');
	$result = mysql_query("SELECT DISTINCT year FROM vehicles WHERE make='$drop_var' AND model='$drop_var2'")
	or die(mysql_error());
	
	echo '<select name="drop_3" id="drop_3">
	      <option value=" " disabled="disabled" selected="selected">Selecteer Jaar</option>';

		   while($drop_3 = mysql_fetch_array( $result ))
			{
			  echo '<option value="'.$drop_3['year'].'">'.$drop_3['year'].'</option>';
			}
	
	echo '</select>';
	echo "<script type=\\"text/javascript\\">
$('#wait_3').hide();
	$('#drop_3').change(function(){
	  $('#wait_3').show();
	  $('#result_3').hide();
      $.get(\\"func.php\\", {
		func: \\"drop_3\\",
		drop_var: $('#drop_1').val(),
		drop_var2: $('#drop_2').val(),
		drop_var3: $('#drop_3').val()
      }, function(response){
        $('#result_3').fadeOut();
        setTimeout(\\"finishAjax_tier_four('result_3', '\\"+escape(response)+\\"')\\", 400);
      });
    	return false;
	});
</script>";
}

//**************************************
//     Second selection results     //
//**************************************
if(isset($_GET['func'])&& $_GET['func'] == "drop_3" ) {
drop_3($_GET['drop_var'], $_GET['drop_var2'], $_GET['drop_var3']);
}
function drop_3($drop_var, $drop_var2, $drop_var3)
{
    include_once('db.php');
        $result = mysql_query("SELECT * FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3'")
    or die(mysql_error());
	
	echo '<select name="drop_4" id="drop_4">
	      <option value="" disabled="disabled" selected="selected">Selecteer Accu</option>';


		   while($drop_4 = mysql_fetch_array( $result ))
				{
				if ($drop_4['accu'] != "") {
			  echo '<option value="'.$drop_4['accu'].'">'.$drop_4['accu'].'</option>';
				}
  }
	echo '</select> ';
    echo '<input type="submit" name="submit" value="Submit" />';
}

?>

For other people that used the same tutorial as I did:)

Thanks StarLion!:slight_smile: I was strugling for a day on this and the good thing is that you let me do it myself:)

Thats what we strive for - noone learns if they are just given the code. :wink:

If you’re still interested, try out these exercises (Now i feel like i’m writing a textbook):

1; remove the function calls. They’re redundant if you only ever use the function once.
2; simplify the script using a [FPHP]switch[/FPHP].
3; try and reduce the functions to a single function. It can be done!
4: try and reduce the javascript in index.html in a similar fashion.

Thanks for the tips:)

I will try to add the functions into one function later on:)

@StarLion; nice one.

Oh, how could I forget.

#5: Sanitize all database queries; switch from mysql to mysqli or PDO

PDO is safer isnt it? Is it hard to manage this with my current functions?

‘safer’ is in the hands of the coder. (not the eye of the beholder, thats just silly.)

PDO certainly CAN be safer, if used appropriately.
Mysql (the library, not the database system) is being deprecated and removed from PHP, which is why i (and PHP’s engineers, and pretty much everybody) strongly recommend changing new scripts over to mysqli (which is the MYSQL-Improved library) or PDO.

If you’re going to actually USE this script anywhere, I heavily suggest looking at rewriting at least the database queries to use prepared PDO statements. As it is, the queries are very glaringly open to attacks.