I have followed a tutorial to dynamically populate dropdown using AJAX to the letter. This is my code config.php
<?php
$con = mysql_connect("localhost", "root","");
if(!$con){
die('Could not connect:' .mysql_error());
}
mysql_select_db('carrental', $con);?>
vehicle_dropdown.php
<?php
include('config.php');
$sql=mysql_query("SELECT vehicleid,vehiclename FROM tbl_vehicles");
if(mysql_num_rows($sql)){
$data = array();
while (&row=mysql_fetch_array($sql)){
$data[] = array(
'id' => $row['vehicleid'],
'name' => $row['vehiclename']
);
}
header('Content-type: application/json');
echo json_encode($data);
}?>
Vehicle.php
<?php
include('config.php');
?>
<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
function Vehicle() {
$('#vehicledll').empty();
$('#vehicledll').append("<option>Loading.....</option>");
$.ajax({
type: "POST",
url: "vehicle_dropdown.php",
contentType: "application/json charset=utf-8",
dataType: "json",
success: function (data) {
$('#vehicledll').empty();
$('#vehicledll').append("<option value='0'>--Select Country--</option>");
$each(data, function (i, item) {
$('#vehicledll').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
},
complete: function () {
}
});
}
$(document).ready(function () {
Vehicle();
});
</script>
</head>
<body>
<select id="vehicledll"></select>
</body>
</html>
However when I run the page the dopdown only displays the message "Loading...." Please help
$each(data, function (i, item) {
$('#vehicledll').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
should be
$.each(data, function (i, item) {
$('#vehicledll').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
});
You have missed a .
after $
and contentType
should be contentType: "application/json; charset=utf-8",
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.