Skip to content
Advertisement

How to handle error from controller using PJAX in YII2?

I am using Yii2 Pjax widget which is unable to throw error from controller due to which I am unable to log error for users when there is any error coming from the controller.

PJAX code

 <?php Pjax::begin([
            'id' => 'createBucketPjax',
            'timeout' => 4000,
            'formSelector' => '#createBucketForm',
            'enablePushState' => false,
            'clientOptions' => [
                'skipOuterContainers' => true,
                'error' => new JsExpression("function(event) { 
                    alert('Anything');
                }"),
            ]
        ]); ?>

CONTROLLER code:

   if(!$fieldModel->save()){
                        $transaction->rollBack();
                        //Here I want to send error 
                        $error = $fieldModel->getErrorsString();
                        return [
                           'success' => false,'error' => $error
                               ];
                       
                    }else{
 return $this->renderAjax('create', [
                            'model' => $model
                        ]);
}

I have tried below clientOptions but not working

'error' => new JsExpression("function(event) { 
                    alert('Please work');
                }"),

Also used javascript but no help :-

 $(document).on('pjax:error', function(event) {
        console.log(event);
      })

Is there any way from which I can send 404 from controller in yii2 ? That can actually resolve my problem

Advertisement

Answer

From the Yii2 Pjax docs.

In responding to the AJAX request, Pjax will send the updated body content (based on the AJAX request) to the client which will replace the old content with the new one. The browser’s URL will then be updated using pushState. The whole process requires no reloading of the layout or resources (js, css)

You must deal with full form content and not with json.

So you code must look like following (always return the form html back):

if(!$model->save()){
   $transaction->rollBack();
}

return $this->renderAjax('create', [
   'model' => $model
]);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement