I have the following ajax code:
$.ajax({
type: 'post',
url: '/conversation/test',
data: { conversation: JSON.stringify(<?php echo json_encode($conversation) ?>) },
success: function (response) {
console.log(response);
}
});
Now I have on my test.php:
<?php
$conversation = json_decode($_POST['conversation']);
?>
<?php foreach ($conversation->getUsers() as $conUser) {
// Skip current user
if ($conUser->getId() == UserSession::getUserId()) {
continue;
} ?>
<a href="/<?php echo $conUser->getUri(); ?>/"><?php echo $conUser->getName(); ?></a>
<?php } ?>
And my response on the console is:
<br />
<b>Fatal error</b>: Call to undefined method stdClass::getUsers() in <b>/Users/msalamanca/PhpStorm/pinporn/trunk/application/views/default/conversation/test.php</b> on line <b>8</b><br />
I don't understand what I am doing wrong here.
$conversationis just decoded JSON you passed to ajax?json_decodeis just for converting JSON string to array - please review us3.php.net//manual/en/function.json-decode.php. If you want to use gettergetUsers()you need to implement some class with properties and getters/setters. You cannot use getter on array.json_decodereturns an object by default, and only returns an array if you explicitly tell it to by using the second parameter. That being said, the sentiment of your post is correct. There is no way for PHP to know that the JSON should be converted into some class that has a specific method.$conversationhereecho json_encode($conversation)? And what exactly is it that you're trying to accomplish?