I have seen that some people asked before similar questions but none of them answers my problem. I have a question regarding ajax and php. In both of them I am relatively beginner.
What I try to do is a so-called: chained select boxes. I want to have 2 dropdown menus. When I select a value from the first one, then the second dropdown menu it gets populated from a mysql database.
For this purpose I use jquery, ajax, php and mysql.
I was trying to find some examples online but all of them seem rather complicated to me (I guess cause I am beginner).
I decided to make something of my own but I got stacked. I am not sure if the logic is correct.
So here we go (I will include only relevant code here):
Using jquery I send an ajax request:
$("#loc").change(function(){
var val = ($('#loc').val());
$.ajax({
type:'POST',
url:'query.php',
data: {val:val},
success:function(response){
$("#x").html(response);
} });
});
"loc" is the id of the first dropdown menu. I get the value and I send it to query.php
query.php has the following lines of code:
<?php
include('connect.php');
$area = $_POST['val'];
$query ="SELECT DISTINCT activity FROM main ORDER BY 1 where n_city='$area'";
$result = mysqli_query($dbcon, $query) or die('no available data');
$options="";
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
$activity=$row["activity"];
}
?>
Now I am trying to figure out two things. 1) What should I return in the success function so I get a form which is populated with the results from the query? 2) Second and most important, is my idea actually correct or there is some logical mistake that I am missing?
Thanks a lot. Dimitris
whileloop just build all the<option>tags you need for the #x<select>. A good thing is to avoid that direct $area variable injection, use a prepared statement instead. And you could get fancy returnin a JSON to parse in jquery instead of the<option>tags.