I have a project in Laravel + socket.io , I need to access a specific field in the json being broadcasted. Here is the code.
socket.js
redis.on('message', function(channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event,message.data);
});
In my client socket, I have this.
socket.on("comment-channel:App\\Events\\CommentEvent", function(message){
alert(message.data);
});
then this will successfully, alert this.
[{
"id": 136,
"content": "dffsadf",
"user_id": "1",
"task_id": "33",
"created_at": "2016-03-29 10:47:19",
"user": {
"id": 1,
"first_name": "Hulk",
"last_name": "Hogan",
"username": "",
"email": " hulhogan@yahoo.com",
"company_id": "1",
"role_id": "0",
"photo": "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",
"position": "asdfsadf",
"phone": "+75843857834",
"city": "",
"country": "Singapore",
"timezone": "",
"created_at": "2016-03-10 04:16:24",
"updated_at": "2016-03-10 07:54:12",
"deleted_at": null
}
}]
Then when I try this
alert(message.data.task_id);
or
alert(message.data['task_id']);
I get 'undefined'..
How can I access, the task_id?Thank You!!!!
message.data
seems to be an array, try alert(message.data[0].task_id);
Edit: If it doesnt work the problem is not there...
var message = {
data : [{
"id" : 136,
"content" : "dffsadf",
"user_id" : "1",
"task_id" : "33",
"created_at" : "2016-03-29 10:47:19",
"user" : {
"id" : 1,
"first_name" : "Hulk",
"last_name" : "Hogan",
"username" : "",
"email" : " hulhogan@yahoo.com",
"company_id" : "1",
"role_id" : "0",
"photo" : "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",
"position" : "asdfsadf",
"phone" : "+75843857834",
"city" : "",
"country" : "Singapore",
"timezone" : "",
"created_at" : "2016-03-10 04:16:24",
"updated_at" : "2016-03-10 07:54:12",
"deleted_at" : null
}
}
]
};
alert(message.data[0].task_id);
Edit 2 are you sure your message.data
is not parsed as string ?
try to cast as json object
var message = {
data : '[{\r\n' +
' "id" : 136,\r\n' +
' "content" : "dffsadf",\r\n' +
' "user_id" : "1",\r\n' +
' "task_id" : "33",\r\n' +
' "created_at" : "2016-03-29 10:47:19",\r\n' +
' "user" : {\r\n' +
' "id" : 1,\r\n' +
' "first_name" : "Hulk",\r\n' +
' "last_name" : "Hogan",\r\n' +
' "username" : "",\r\n' +
' "email" : " hulhogan@yahoo.com",\r\n' +
' "company_id" : "1",\r\n' +
' "role_id" : "0",\r\n' +
' "photo" : "\/assets\/apps\/img\/photos\/lvrv5VOGRskwPHvFVakp.jpeg",\r\n' +
' "position" : "asdfsadf",\r\n' +
' "phone" : "+75843857834",\r\n' +
' "city" : "",\r\n' +
' "country" : "Singapore",\r\n' +
' "timezone" : "",\r\n' +
' "created_at" : "2016-03-10 04:16:24",\r\n' +
' "updated_at" : "2016-03-10 07:54:12",\r\n' +
' "deleted_at" : null\r\n' +
' }\r\n' +
' }\r\n' +
' ]'
};
var obj = JSON.parse(message.data);
alert(obj[0].task_id);