jamcoupe
jamcoupe

Reputation: 1452

Outputting php json data

I have a small problem when I get old messages from my database. I can't use the information using the usual console.log(data.message); because this comes back undefined but when I use console.log(data);

[{"message":"Hello","time":{"sec":1328831312,"usec":699000},"user":"4f326ef17edae18d11000000"},{"message":"Heyyy","time":{"sec":1328831324,"usec":48000},"user":"4f33a3db7edae17736000000"},{"message":"afasfasd","time":{"sec":1328831966,"usec":960000},"user":"4f33a3db7edae17736000000"},{"message":"asdfasdfasdf","time":{"sec":1328831968,"usec":283000},"user":"4f33a3db7edae17736000000"},{"message":"old message","time":{"sec":1328831969,"usec":234000},"user":"4f33a3db7edae17736000000"}]

I search my database for the messages between two users and then loop through the data like this

$messages = array();
for($i=0; $i<count($cursor['messages']); $i++){
    $object = array('message'=>$cursor['messages'][$i]['message'],
                    'time'=>$cursor['messages'][$i]['time'],
                    'user'=>$cursor['messages'][$i]['user']);

    $messages[] = $object;
}
echo json_encode($messages)

I want to be able to get the users ID, message and time the message was sent so that I can append each to my chat history but I can stuck on outputting the information.

Upvotes: 0

Views: 111

Answers (1)

tomfumb
tomfumb

Reputation: 3759

It looks like your response is contained within an array [].

Assuming your paste is representative you should be able to get the data you want with

data[i].message

and

data[i].time.sec

etc.

In your JS you will want to loop up to data.length to retrieve each message.

Edit: Looks like you're not parsing the string after receiving it. Please try the following

var parsedData;
if(JSON && JSON.parse) {
    parsedData = JSON.parse(data);
}
else {
    parsedData = eval(data); 
}

alert(parsedData[0].message);

Upvotes: 2

Related Questions