I have read other questions but my problem is little different. I am getting the response in a format like this from an eloquent query in Laravel.
[{"id":1,"message":"sdfsdf","message_for":1,"message_by":2},{"id":2,"message":"hello","message_for":4,"message_by":2},{"id":4,"message":"hi how are you?","message_for":1,"message_by":2}]
There is no variable attached to each object like in this question div1
, div2
etc.
This is my ajax
code
$.ajax({
url: '/chat',
type: 'POST',
dataType: 'json',
data: { id: sessionStorage.getItem('user_id') },
//cache: false,
success:function(data){
/*var x;
for(x in data){
/!*$("span.messages").fadeIn("slow").append(data[x]);
$("span.messages").append("<br>");*!/
}*/
},
error: function(data) {
console.log('data is :'+data.id);
console.log("error");
}
});
And this is my controller function from where I am returning the response.
public function getUserMessages(Request $request){
$id = (int)$request->request->get('id');
$messages = Message::where('message_by' , $id)->get()->toJson();
return $messages;
}
I tried using data["message"]
but it does not work. Using data[0]
will return [
.