0

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 

  instancee();
  // 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');
          //$response[$i]['name'];
          option.value = jsonData['id'][i];
          option.text = jsonData['name'][i];
          selectList.appendChild(option);
        }
      }
    }
  }

  // 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 
  xhr.open('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)) {
  $id=$result2['idprof'];
  $profesor=$result2['ime']. " ".$result2['prezime'];

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

  echo json_encode($data);      
}

alert(var) 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?

3
  • 1
    You could call val.toString() and check whether its really a JSON. Commented Nov 10, 2014 at 9:54
  • 2
    JSON.parse('{"id":["2"],"name":["Zdravko Topic"]}') works fine, although you do not need to cast array in your php code. Commented Nov 10, 2014 at 9:55
  • It is really JSON.. I cant parse like that because value wont be "id":["2"],"name":["Zdravko Topic"] always, question is how to parse multidimensional array with values ('id' => $varid, 'name'=> $varname) and put that into dropdown like <option value="$varid"> $varname </option> Commented Nov 10, 2014 at 10:08

1 Answer 1

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

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 "object.property".

Sign up to request clarification or add additional context in comments.

4 Comments

looks promisinig (50% of answer). But still cannot JSON.parse 2d array.. I am getting unexpected token { error at: var jsonData = JSON.parse(val);
The json parses just fine for me, also you're storing both the id and the name as an individual array, try to store it as 'id' => $id and 'name' => $professor in ajax.php
I have corrected array in ajax.php as you said...And fixed JSON.parse, however JSON.parse only work when I have only one database query like {"id":["2"],"name":["Zdravko Topic"]}, when i have multiple queries like : {"id":["1"],"name":["Name Lastname"]}{"id":["2"],"name":["Zdravko Topic"]}, then it gives me unexpected token again. Could you try on that example? Oh and yeah, jsonData.length doesnt work at all, it says undefined.. When I use only one database query like: {"id":["2"],"name":["Zdravko Topic"]} without for loop, then it works like charm,,, litlle bit confusing,eh
Got it,, your code is good... I was creating not valid JSON in my php script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.