How to use the render method inside a controller action called by ajax

Hi, I’m trying to load some more content in a view by pressing a button. Pressing the button triggers an ajax listener calling an action supposed to be rendering some more content in the current view.

The ajax is successful but nothing is rendered in addition to the initial view (I also tried renderPartial but it does not work neither).

Here is the important content of the view :

<?php
    $nextFlow = Url::to(['dashboard/fetch-flow-ajax', 'user' => $user->id, 'page' => $pageNumber]);
?>
<button class="testAjax">Test</button>
<?php
    $this->registerJs("
    jQuery(document).ready(function () {
        $('.testAjax').on('click', function(){
            $.ajax({
                url: '$nextFlow',
                type: 'POST',
                success: function(){
                    Messenger().post({
                        message: 'flow loaded',
                        type: 'success',
                        hideAfter: 5,
                        hideOnNavigate: true,
                 });
               }
             })
          }) 
       });
    ")
 ?>

When clicking the button it triggers this action :

public function actionFetchFlowAjax($user, $page, $pageSize = self::PAGE_SIZE)
{
    $comment = new Comment();

    $data = $this->getFlowForUser($user, $page, $pageSize);

    return $this->render('_items', [
        'user' => $user,
        'comment' => $comment,
        'dataProvider' => $data,
    ]);
}

So this action get called successfully but nothing is rendered in the initial view despite using the render method.

In the ‘_items’ view I only put a <p>ok</p> to test if the whole thing works and previously it had more complex content. But it is not rendered either way.

If you have any clue on why it does not work, I thank you in advance.

Open your Yii2 debug toolbar & browser DEV tools in order to check the data transmitted & received during the AJAX request in order to make sure that there is no error.

By reviewing your code i notice that in the JavaScript code in the AJAX success function you simply display a success message but there is no code to actually retrieve the server response & insert/append it to a DOM element.

1 Like

Everything is green returning a status 200.

So I guess that I lack the code part where I’m supposed to insert the new content to the DOM. I thought the render method would do it.

Do I need to return the data without the render method or do I need to keep the render method in order to get it with AJAX ? I guess there is something I don’t understand with using the render method in controllers.
https://www.yiiframework.com/doc/api/2.0/yii-base-controller#render()-detail

Thank you.

Edit: By using .append(), it works, but I get a warning about Synchronous XMLHttpRequest for user’s experience.

First of all in case you wish to render a partial view you would probably want to use renderPartial() instead of render(), this way the layout will not be applied to the returning view.

Furthermore i would wrap the rendered view within an array, json encode it and then send this as a result back to the AJAX request. A more elegant approach would be to change the response format of the method or entire controller via \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

1 Like