Reputation: 416
I currently am attempting to create my own instant messenger for my site (NOT using a plugin - am attempting to hand make this for learning purposes) and I am looking to try to send an ajax request to the server for a list of all messages between two users. My question is this: can ajax 'read' a collection of Message objects sent from Laravel (doubt it) or does it need to be formatted in a certain way/manner? I initially thought to use lists to get the sender_id along with the message (the order is by date by default), however, I don't think that javascript can read PHP's (not)-arrays. The only viable solution I have came up with thus far is to send either 1 array with sender_id followed by the message for the entire conversation OR 2 arrays- one with all sender_id's in order and a second with all messages in order.
Thanks.
Upvotes: 2
Views: 2723
Reputation: 605
You can use JSON for communicating between PHP and JavaScript (look up PHP json_encode and json_decode functions), it'll allow you to pass complex arrays almost natively between the languages.
EDIT: a few examples to give some indication how it works, I'm using jQuery for my examples here
Requesting information from a PHP script via AJAX:
$.ajax({
method: 'GET',
dataType: 'json',
success: function(data) {
for (i in data.messages) {
output(data.messages[i]);
}
}
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can output:
$messages = array(
array(
'id' => 1,
'message' => 'Awesome',
'sender' => array(
'id' => 1, 'name' => 'John',
),
),
);
echo json_encode(array('messages' => $messages));
Sending information using JSON via AJAX:
// Example data object, you can have this infinitely nested
var data = [
{id: 1, "message": "test" }
];
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
var output = function(message) {
console.log(message.id);
console.log(message.sender.id);
};
The PHP script can then read this using:
$data = json_decode(file_get_contents('php://input'), true);
// This becomes a simple 2D PHP array which is an exact representation as your JS object. The above example data can be output as:
foreach ($data as $message) {
echo $message['id'] . ' - ' .$message['message'];
}
Upvotes: 2