lernyoung lernyoung - 3 months ago 6
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

[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]


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:

PHP

<?php

//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;


?>


JQUERY

$(document).ready(function(){

//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){

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

});


Please what could be the problem?? Thank you

Answer

Try deserializing the response:

var array = JSON.parse(response);

EXPLANATION

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).