I scrapped this code to check if the mechanism works. Actually what I needed to achieve was to populate a "city dropdown" as per the selection made with the "state" dropdown. The HTML code is as follows.
<select id="id"></select>
<select id="state"></select>
<select id="city"></select>
The Ajax call is as follows.
$(document).on("change", '#state', function(e) {
var state = $(this).val();
$.ajax({
type: "POST",
data: {state: state},
url: 'get_name_list.php',
dataType: 'json',
success: function(json) {
var $el = $("#city");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});
The PHP code encodes the list of values into a JSON with the following structure.
As a test, I inserted the JSON into a Database table and it is working until this point. So it is not a theoretical process. It works until this point in the code.
The JSON structure is as follows.
[{"name":"Alappuzha"},{"name":"Ernakulam"},{"name":"Idukki"},{"name":"Kannur"},{"name":"Kasaragod"},{"name":"Kollam"},{"name":"Kottayam"},{"name":"Kozhikode"},{"name":"Malappuram"},{"name":"Palakkad"},{"name":"Pathanamthitta"},{"name":"Thiruvananthapuram"},{"name":"Thrissur"},{"name":"Wayanad"}]
Then I echo the JSON.
But the dropdown back at the first page is not getting populated. The PHP file is as follows.
$json= array();
$id=$_POST["id"];
//echo $sample;
//mysqli_query($mysqli,"INSERT into test_tablr values('','$id')") or die(mysqli_error($mysqli));
if ($result = $mysqli->query("SELECT name FROM geo_locations WHERE parent_id =$id ")) {
while ($row = mysqli_fetch_assoc($result)) {
$json1[] = $row;
}
$json=json_encode($json1);
}
mysqli_query($mysqli,"INSERT into test_tablr values('','$json')") or die(mysqli_error($mysqli));
echo $json;
But unfortunately, the dropdown is not getting populated. Any lights?
Try This in jQuery:
var $el = $("#city");
$el.empty(); // remove old options
$el.append($("<option value=''>Please Select</option>");
$.each(json, function(value, key) {
$el.append($("<option value='"+ value +"'>"+key+"</option>");
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments