Reputation: 33
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.
Upvotes: 1
Views: 478
Reputation: 33
Thank you all for your answers, they helped me in finding a solution for my problem. I ended up rewriting the code and using jquery and Ajax. Here is the working solution, for anyone who has the same or similar problem as me.
Ajax:
<?php
//Include database configuration file
include('dbConfig.php');
if(isset($_POST["marque_id"]) && !empty($_POST["marque_id"])) {
//Get all state data
$query = $db->query("SELECT * FROM vehicule_modele WHERE marque_id = ".$_POST['marque_id']." ORDER BY modele_name ");
//Count total number of rows
$rowCount = $query->num_rows;
//Display model list
if($rowCount > 0){
echo '<option value="">Select model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['modele_id'].'">'.$row['modele_name'].'</option>';
}
}else{
echo '<option value="">Model not available</option>';
}
}
if(isset($_POST["modele_id"]) && !empty($_POST["modele_id"])){
//Get all energy data
$query = $db->query("SELECT energie_name FROM vehicule_energie WHERE energie_id = (SELECT energie_id FROM vehicule_modele WHERE modele_id = ".$_POST['modele_id'].")");
//Count total number of rows
$rowCount = $query->num_rows;
//Display energy list
if($rowCount > 0) {
echo '<option value="">Select energy</option>';
while($row = $query->fetch_assoc()){
echo '<option value = "'.$row['energie_id'].'">'.$row['energie_name'].'</option>';
}
}else{
echo '<option value="">Energy not available</option>';
}
}
?>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#car').on('change',function(){
var carID = $(this).val();
if(carID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'marque_id='+carID,
success:function(html){
$('#test1').html(carID);
$('#model').html(html);
$('#energy').html('<option value="">Select model first</option>');
}
});
}else{
$('#model').html('<option value="">Select car first</option>');
$('#energy').html('<option value="">Select model first</option>');
}
});
$('#model').on('change',function(){
var modelID = $(this).val();
if(modelID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'modele_id='+modelID,
success:function(html){
$('#test').html(modelID);
$('#energy').html(html);
}
});
}else{
$('#energy').html('<option value="">Select model first</option>');
}
});
});
</script>
HTML:
<?php
//Include database configuration file
include('dbConfig.php');
//Get all car data
$query = $db->query("SELECT marque_name,marque_id FROM vehicule_marque order by marque_name");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="car" id="car" >
<option value="">Select Car</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['marque_id'].'">'.$row['marque_name'].'</option>';
}
}else{
echo '<option value="">Car not available</option>';
}
?>
</select>
<div id="test1"></div>
<select name="model" id="model">
<option value="">Select car first</option>
</select>
<div id="test"></div>
<select name="energy" id="energy">
<option value="">Select model first</option>
</select>
I should point out how my tables looked like in order to make the code more clear:
energie_id energie_name
1 diesel
2 essence
3 electric
marque_id marque_name
1 audi
2 mercedes
3 bmw
modele_id marque_id energie_id modele_name
1 1 1 A4
2 1 1 Q5
3 2 2 SLK
Upvotes: 1
Reputation: 48207
I ask a similar question a few days back. How return null for an empty combo box instead of 0?
You need to handle the cascade combos using javasscript. This example use c# to create the data so the validation error is something handle by the framework. But the view page is updated using javascript
You use Jquery getJson to update the combo when a selected item change.
<script type="text/javascript">
var localityUrl = '@Url.Action("FetchLocalities")';
var subLocalityUrl = '@Url.Action("FetchSubLocalities")';
var coodinatesUrl = '@Url.Action("FetchCoordinates")';
var localities = $('#SelectedLocality');
var subLocalities = $('#SelectedSubLocality');
$('#SelectedCity').change(function() {
localities.empty();
subLocalities.empty();
$.getJSON(localityUrl, { ID: $(this).val() },function(data) {
if (!data) {
return;
}
localities.append($('<option></option>').val('').text('Please select'));
$.each(data, function(index, item) {
localities.append($('<option></option>').val(item.Value).text(item.Text));
});
});
$.getJSON(coodinatesUrl, { ID: $(this).val() }, function(data) {
console.log(data);
});
})
$('#SelectedLocality').change(function() {
subLocalities.empty();
$.getJSON(subLocalityUrl, { ID: $(this).val() },function(data) {
if (!data) {
return;
}
subLocalities.append($('<option></option>').val('').text('Please select'));
$.each(data, function(index, item) {
subLocalities.append($('<option></option>').val(item.Value).text(item.Text));
});
});
})
</script>
Here is the working demo https://dotnetfiddle.net/1bPZym
Upvotes: 0
Reputation: 108
I would use Jquery to do this trick, like this
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
$('#inputCar').change(function(){
var selected = $(this).find(':selected').attr('value');
var newOptions = {"Option 1": "value1",
"Option 2": "value2",
"Option 3": "value3"
};
var $el = $("#inputModele");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
});
Upvotes: 0