I have a project to do where I need to make a search form, where the user selects an item from the first drop down list and then, depending on his choice, in the second drop down the items related to the first choice will show, and so on. I found an example on this site, and I followed the one that uses php and mysql but I encountered some problems.
After successfully connecting to the database, I had the following code.
Javascript:
function reload(form){
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='search.php?inputCar=' + val ;
}
PHP:
@$cat=$_GET['cat'];
echo $cat;
// Use this line or below line if register_global is off
if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
echo "Data Error";
exit;
};
$query_car="SELECT DISTINCT marque_name,marque_id FROM vehicule_marque order by marque_name";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT modele_name FROM vehicule_modele where marque_id=$cat order by modele_name";
} else {
$query_modele="SELECT DISTINCT modele_name FROM vehicule_modele order by modele_name";
};
HTML:
<div class="form-group col-4">
<label for="inputCar">Choose Car</label>
<select name="cat" id="inputCar" class="form-control" onchange="reload(this.form)">
<option value=''>Choose one...</option>
<?php
foreach ($conn->query($query_car) as $noticia2) {
if($noticia2['marque_id']==@$cat){echo "<option selected value='$noticia2[marque_id]'>$noticia2[marque_name]</option>"."<BR>";
} else {
echo "<option value='$noticia2[marque_id]'>$noticia2[marque_name]</option>";
}
};
?>
</select>
</div>
<div class="form-group col-4">
<label for="inputModele">Choose Model</label>
<select name="imputModele" id="inputModele" class="form-control">
<option>Choose one...</option>
<?php
foreach ($conn->query($quer) as $noticia) {
echo "<option value='$noticia[modele_name]'>$noticia[modele_name]</option>";
};
?>
</select>
</div>
The problem I'm having with this code is, that when I select the first item, it doesn't auto reload, and it doesn't set the selected value in the url. But, if I manually write the ?inputCar= + val
, it does the reload and it shows the first drop down as it should be. The error in the console that I'm getting is reload is not defined
.
I tried searching for a solution, but despite multiple questions asked about this topic, I can't seem to find a solution for my particular problem. I'm new to all this, so I attempted to do it this way instead of using Ajax which is still pretty complicated for me. If anyone can see what I'm doing wrong and point me in the right direction, I would greatly appreciate it.