lernyoung
lernyoung

Reputation: 263

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

Upvotes: 3

Views: 47

Answers (3)

kapantzak
kapantzak

Reputation: 11750

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

Upvotes: 1

Haresh Vidja
Haresh Vidja

Reputation: 8496

Keep your server side PHP script code neat and clean

  1. Start PHP block from first character of first line.
  2. Do not close php block if there is no output in HTML format.
  3. Use ob_clean() function before echo output in is your are in developer mode and display error is enabled.

for example

ob_clean();
echo json_encode($array);

In client side, if you are getting JSON response in ajax, pass dataType:'json' in ajax option

$.ajax({
    url:"testing.php",
    type:"post",
    dataType:"json",
    success:function(response){
        console.log(response[0].f +" "+ response[0].l);
    }
});

Upvotes: 1

passion
passion

Reputation: 1360

 $.ajax({
    url:"testing.php",
    type:"post",
    success:function(response){

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

You get a string from php , need turn the string into a json object .

You have to learn to debug your code to find what is going wrong I guess .

Upvotes: 2

Related Questions