Andrija Glavas Andrija Glavas - 1 year ago 55
PHP Question

Dynamical creating dropdown from database data in PHP & Ajax

I am trying to make dynamical dropdown that will be populated by data collected from database. I am stuck at parsing data from multidimensional array sent by PHP file. My code:

Part of HTML file (only the responsible JavaScript (Ajax function))

function mentor() {
// 1. Create XHR instance - Start
var oblast = document.getElementById("oblast").value; //previous dropdown from which I need to create next one
document.getElementById("mentorr").innerHTML = ""; //emtpy the dropdown I need to create

// 1. Create XHR instance - End

// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var val = xhr.responseText;
alert(val); //just a check to see does it get correct data, and it get, everything is OK so far

var jsonData = JSON.parse(val);
var selectList = document.getElementById('mentorr'); //id of the dropdown I need to create

for (var i in jsonData) {
var option = document.createElement('option');
option.value = jsonData['id'][i];
option.text = jsonData['name'][i];

// 2. Define what to do when XHR feed you the response from the server - Start

// 3. Specify your action, location and Send to the server - Start'POST', 'ajax.php');

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("oblast=" + oblast);

Part of ajax.php file that fetches data and sends to HTML:

$queryData1 = mysql_query("SELECT * FROM profesori WHERE idprof = '$prof'");

while($result2 = mysql_fetch_array($queryData1)) {
$profesor=$result2['ime']. " ".$result2['prezime'];

$data = array
'id' => array($id),
'name' => array($profesor)

echo json_encode($data);

line of code gives this:

enter image description here

So data is corretly fetched from database and sent to HTML. But the problem is in populating dropdown menu (parsing data). Error in console in "unexpected token {" in the line

var jsonData = JSON.parse(val);

Does anyone know how to fix this?

Answer Source
for (var i = 0; i < jsonData.length; i++) {
    var option = document.createElement('option');
    option.value = jsonData[i].id;
    option.text = jsonData[i].name;

Should do the trick, JSON.parse returns json objects, you can loop through the objects using an index and fetch properties of an object like this "".