I am trying to create a dependent dropdown using php and ajax. What I am expecting is when the ‘Make’ of car is selected the relevant car models should automatically load on the ‘Model’ dropdown. I have manged to do the preloading of ‘Make’ of cars. But the ‘Model’ dropdown remains empty. I have used a single tale and in sql statement used (select model where make= selected make). here is my code
php
<form method="GET">
<div class="form-group">
<select class="form-control" name="make" id="make">
<option value="" disabled selected>--Select Make--</option>
<?php
$stmt=$pdo->query("SELECT DISTINCT make FROM cars WHERE cartype='general' ");
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?= $row['make']; ?>"> <?= $row['make']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<select class="form-control" name="model" id="model">
<option value="" disabled selected>--Select Model--</option>
</select>
</div>
.......
....
.....
script
<script type="text/javascript">
$(document).ready( function () {
// alert("Hello");
$(#make).change(function(){
var make = $(this).val();
$.ajax({
url:"filter_action.php",
method:"POST",
data:{Make:make},
success: function(data){
$("#model").html(data);
});
});
});
</script>
filter_action.php
<?php
include('db_config2.php');
$output='';
$stmt=$pdo->query("SELECT DISTINCT model FROM cars WHERE cartype='general' AND make= '".$_POST['Make']."'");
$output .='<option value="" disabled selected>--Select Model--</option>';
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$output .='<option value="'.$row["model"].'">'.$row["model"].'</option>' ;
}
echo $output;
?>
2
Answers
There appeared to be a couple of mistakes in the Javascript that would have been obvious in the developer console and your PHP had left the mySQL server vulnerable to sql injection attacks.
The direct use of user supplied data within the sql opened your db to sql injection attacks. To mitigate this you need to adopt
"Prepared Statements"
– as you are using PDO anyway this should be a matter of course.I have try this using
php pdo
.first i have create a 3 files.
db.php
htmlDropdown.php
modelAjax.php
here,
db.php
file can contain my database connection code. andhtmlDropdown.php
file contain my dropdown for car and models. andmodelAjax.php
file contain ajax to fetch all models.db.php
htmlDropdown.php
modelAjax.php