Submit form via ajax

Is there any different way of submitting form via ajax a part from using serialize. I tried to used it but it is not submitting the data( the data are not being saved):

[list=1]

[*]Javascript(form submission code):




var formulaire = $("#myform"); 

formulaire.submit(function(e) {

  var url = formulaire.attr('action'); 

  $.ajax({

      type:"POST",url: url,

      data: formulaire.serialize(),

      success:function(data){

          $('#cop').remove();

          $(data).insertAfter('#pop');},

     error:function(){

            $('#cu').addClass('text-danger');}

      });

e.preventDefault();  });



[*]Controller:




 public function actionRegister()

    {

        if (!\Yii::$app->getModule('user')->enableRegistration) {

            throw new NotFoundHttpException;

        }

        

        $model = \Yii::createObject(RegistrationForm::className());

        $this->performAjaxValidation($model);

        

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

$this->renderAjax('index');

}}



[/list]

Check what your "performAjaxValidation" is doing.

I guess it is sending back the response without returning to this controller.

That’s for validation but what I want is form submission and especially if it has file input

  1. Watch the ‘network’ tab in developer tools (if you use chrome). Errors will be shown

  2. Show code of $model->register() method

  3. Why you validate $model before fill it data?

[list=1]

[*]

[*]Here is the code of Register:


public function register()

    {

        if (!$this->validate()) {

            return false;

        }


        /** @var User $user */

        $user = Yii::createObject(User::className());

        $user->setScenario('register');

        $this->loadAttributes($user);


        if (!$user->register()) {

            return false;

        }


        Yii::$app->session->setFlash(

            'info',

            Yii::t('user', 'Your account has been created and a message with further instructions has been sent to your email')

        );


        return true;

    }

[*]Here is the code:


 protected function performAjaxValidation(Model $model)

    {

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

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

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

            Yii::$app->end();

        }

    }

[/list]

When I submit the form it not saving the data in the database I don’t know why but if I don’t use ajax for submission it’s saving.

I understand now after checking the performAjaxValidation which is stopping the everything with


\Yii::$app->end();

I am overriding a method from someone’s class if I remove performAjaxValidation the ajaxvalidation is not showing if a field data are not valid as it was doing before(putting the label color to red).

One thing I am sure of is :

if I differentiate ajax request for validation(In this case I need to end the application in the method) and ajax for submission(I don’t need to end the application)

This performAjaxValidation will not return to your actionRegister (it will "Yii::$app->end();"), when your request is ajax with post method. That is, if you have successfully submitted your form via ajax, then it will "end" in this method.

I understand now after checking the performAjaxValidation which is stopping the everything with


\Yii::$app->end();

I am overriding a method from someone’s class if I remove performAjaxValidation the ajaxvalidation is not showing if a field data are not valid as it was doing before(putting the label color to red).

One thing I am sure of is :

if I differentiate ajax request for validation(In this case I need to end the application in the method) and ajax for submission(I don’t need to end the application)

While searching I found how I can make the validation work without disturbing the register action. I need is to create a validation action in the controller and in the view I specify the validation url.

Controller:


     public function actionValidate($nameclass)

{

   $model = \Yii::createObject(\Yii::$app->request->get('nameclass'));

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

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

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

            \Yii::$app->end();

        }

}

View:


 <?php $form = ActiveForm::begin([

                    'id'=> 'registration-form',

                    'method'=>'post',

                    'action'=>\Yii::$app->urlManager->createUrl(['registration/register']),

                    'enableAjaxValidation'   => true,

                    'enableClientValidation' => false,

                    'validationUrl' => \Yii::$app->urlManager->createUrl(['site/validate','nameclass'=>get_class($model)]),

                    'options'=>['class'=>'well-sm',

But the problem is the validation url is not working not working(not showing the red or green color) and if I use only performAjaxValidation by removing


\Yii::$app->end();

same problem is coming up.

I’ve gotten the problem with the validationUrl(lack of importing the namespaces(response and activeform)) now it working.

But leaving that ajax validation focusing on the clientsidevalidation there is a problem: When the data are sent to the server to be save it is important to perform check up again but at that time if the model is not valid the response returned is in json format containing the messages and attributes that have errors. When receiving how can I affect it to the form on the client side; each error from the reponse to it field on the form?

Is there any function on client side(js) that I can call passing the response to it?