1

I apologize if this question has been asked before, but I can't seem to get on of them to work for me. The PHP script passes database results to JavaScript like this:

$queryResult =  mysqli_query($dbase, $query);

if ($queryResult) {
  $result = array();
  while($row = mysqli_fetch_array($queryResult)) {
      $result[] = $row;
  }
}

echo json_encode($result);

JavaScript then receives this through AJAX (result of console.log):

[{"id":"1","name":"Babe Ruth","loginID":"babe","loginPW":"babe123"}]

I've tried JSON.stringify, Object.keys(arr), foreach ($arr as $key => $value), for(i in arr), but all to no success.

How can I read this as key-value pairs?

TIA.

2
  • try Json.parse() as described here: w3schools.com/js/js_json_parse.asp Commented Oct 11, 2017 at 20:11
  • Thanks ju. Apparently that was the right method, although it had to be accessed with id keys, as Vasya had indicated (the marked answer). Commented Oct 11, 2017 at 20:42

4 Answers 4

2

You response is array of objects, You can use next code:

var users = JSON.parse(response);

for(var objId in users) {
    // here you can use construction users[objId].your_key

    console.log('id', users[objId].id);
    console.log('name', users[objId].name);
    console.log('loginID', users[objId].loginID);        
    console.log('loginPW', users[objId].loginPW);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, Vasya Zhuryk! It worked perfectly, finally.
1

What you've copied looks like a JS array containing one object.

Assuming your array is arr then:

var obj = arr[0];

console.log(obj.id);

If what you pasted was actually a string, then you'll need to parse that JSON string with var arr = JSON.parse(response); and continue as mentioned above.

1 Comment

Thank you for your suggestion, but it just returned undefined.
1

I think you're looking for JSON.parse, e.g

var user = JSON.parse(response)[0];

// Should print "Babe Ruth"
console.log(user.name);

2 Comments

Thank you for your suggestion, but it just returned undefined.
I tried your original posted code, but must have missed your edit. This works too. Thank you, J0sh0nat0r.
0

You should get the index 0 of your response, then you can manipulate your object.

var response = [{"id":"1","name":"Babe Ruth","loginID":"babe","loginPW":"babe123"}];
response = response[0];

console.log(response.id);

1 Comment

Thank you for your suggestion, but it just returned undefined.

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.