M
M
michaelromanov902016-10-23 18:21:17
Yii
michaelromanov90, 2016-10-23 18:21:17

How to correctly implement ajax response in yii2?

I have a form

$form = ActiveForm::begin([
                    'id' => 'emailsimple',
                    'enableAjaxValidation'   => true,
                    'enableClientValidation' => true,
                    'validationUrl' => '/site/controllers/site/feedback-emailsimple',
                ]);


and there is this controller, and in it the method
public function actionFeedbackEmailsimple()
    {
        Yii::$app->Url->RequestAjax__Check();
        $model = new Emailsimple();
        if ($model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        } else {
            throw new ForbiddenHttpException;
        }
    }


and so, at success, the page reloads. But, of course, this is superfluous, it is necessary to make sure that I get the answer in js.
js events do not have time to be caught, as the page is reloading...
What should I do?)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2016-10-23
@michaelromanov90

Good evening.
Maybe this video will help you.

R
Rustembek Kaliev, 2016-10-23
@rusticus

'Js events can't be caught because the page is reloading...' - do not reload the page, but send form data via ajax, like this

datastring = $("form").serialize();
$.ajax({
  url: "/controller/",
  data: datastring,
  type: "GET",
  dataType: "json",
  success: function(data){
  },
  error: function(data){
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question