Problem With Json Format On Ajax Request On Validation

I have the following code which I want to do ajax validation.


public function actionCreate() {

        $model = new Filter();


        $this->performAjaxValidation($model);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {


            return $this->redirect(['view', 'id' => $model->id]);

        } 

        else {

            return $this->render('create', [

                        'model' => $model

            ]);

        }

    }

If I write this below code it works.


protected function performAjaxValidation($model) {

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

            //Yii::$app->response->format = 'json';

            

            echo json_encode(ActiveForm::validate($model));

            Yii::$app->end();

        }

    }

But why it does not work with this code? It throws error in the console.


protected function performAjaxValidation($model) {

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

            Yii::$app->response->format = 'json';

            

            return ActiveForm::validate($model);


        }

    }

Thanks in advance for your response.

It’s better to use:




use yii\web\Response;


...


Yii::$app->response->format = Response::FORMAT_JSON;



instead of hardcoded ‘json’.

What kind of error is thrown in the console?

The response should contain the json format of validation error only. But I am getting the json response from the whole page like "<!DOCTYPE html>\n<html lang=\"en-US\">\n<head>\n <meta charset=\"UTF-8\"\/>\n …

That happens because you returning JSON in separate protected method performAjaxValidation().

You call that method in controller action, but JSON returned inside that method and not in the action. So after calling that method code execution continues and you get that error.

Your another approach works, because you call echo and immediately after that stop further code execution by calling Yii::$app->end().

You can see AJAX validation example from official docs here.

If you need to keep that functionality in separate method you should restructure the method and its call so JSON returned in controller action.

Also if you want you can try to move that functionality to behavior and attach it to each action where you want to check AJAX request first and return validation errors for model (you can pass model class as option).