lernyoung lernyoung - 1 year ago 74
jQuery Question

How to access entry in the javascript object array

I assigned a JSON result from php to a javascript variable.
The result returned looks like below but it gives me undefined undefined


I simple know this look like a javascript array with two objects.
I am trying to access the data inside the objects but to no avail.
Below is script:



//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);

while($row = mysqli_fetch_assoc($q)){
$array[] = $row;


$json = json_encode($array);
echo $json;




//checking online users

var array = response;
console.log(array[0].f +" "+ array[0].l);


Please what could be the problem?? Thank you

Answer Source

Try deserializing the response:

var array = JSON.parse(response);


The response you get from the ajax call is of type string, so you have to convert it to an object. That's what JSON.parse() method do: it parses the JSON string and creates the object that this string represent, following specific rules (The parsed string must be in a valid JSON format).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download