简体   繁体   中英

How can I send a php object through ajax using json?

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.

Finally I understood what I was doing wrong. So on my view, I did the following:

    <div id="messages-widget">

    </div>

    <!--  Updates the conversation display and check for new messages  -->
    <script>
        $(document).ready(function () {

            $.post( "/conversation/messages", { conId: <?php echo $conversation->getId(); ?> })
                 .done(function (data) {
                      $('#messages-widget').html(data);
            });


        });

    </script>

Then in my Controller I just did the following:

    public function messages($args=array()) {

        $conId = $args['conId'];

        // Get current conversation
        $conversation = ConversationModel::getConversationById($conId);

        DataHolder::getInstance()->addObject('conversation', $conversation);
    }

So like this, my view will have the conversation object that I wanted, with its properties. Doing it like this, I can use the getters and setters that I needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM