kaynewilder
kaynewilder

Reputation: 853

Yii2 No-refresh Page After Submitting Modal Form

I have a Create Purchase page. It has a Supplier drop down field where I can Add New Supplier that shows a modal when clicked. In the modal is a form for adding a new supplier. After I create a new supplier and click the submit button, the page will be refreshed.

Here is a screenshot: enter image description here

The page is refreshed due to the redirect function in my action controller:

$model->refresh();
return $this->redirect(['index', 'id' => $session['user_id']]);

I know that Ajax can maybe solve this problem but I don't know how to start. How do I get the data from my modal form after clicking the Create button to use it in my Ajax function without going through my controller (just for front end display)?

Upvotes: 2

Views: 11342

Answers (1)

Akshay Vanjare
Akshay Vanjare

Reputation: 655

Disable Yii client validation by adding following line in ActiveForm options

'enableClientValidation'=>false

Now add your javascript code on form submission to collect your form data and send it to server. Yii will validate this data and if there are any validation errors, we will send it back

$this->registerJs('
    $("#contact-form").submit(function() {
        $(".form-group").removeClass("has-error");      //remove error class
        $(".help-block").html("");                      //remove existing error messages

        var form_data = $("#contact-form").serialize();
        var action_url = $("#contact-form").attr("action");

        $.ajax({
            method: "POST",
            url: action_url,
            data: form_data
        })
        .done(function( data ) {
            console.log(data);
            if(data.success == true)    {       //data saved successfully 

            }   else    {       //validation errors occurred
                $.each(data.error, function(ind, vl) {      //show errors to user
                    $(".field-contactform-"+ind).addClass("has-error");
                    $(".field-contactform-"+ind).find(".help-block").html(vl[0]);
                });
            }

        });
        return false;
    });', \yii\web\View::POS_READY, 'my-ajax-form-submit');

Now Made some changes in your controller action

public function actionContact()
{
    $model = new ContactForm();
    if ($model->load(Yii::$app->request->post())) {
        $success = false;
        $error = [];
        if($model->contact(Yii::$app->params['adminEmail']))    {
            $success = true;
        }   else    {
            $error = $model->getErrors();       //get validation error messages
        }
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Content-type: application/json');
        echo json_encode(['success' => $success, 'error' => $error ]);

        Yii::$app->end();
    } else {
        return $this->render('contact', [
            'model' => $model,
        ]);
    }
}

And it's done.

Upvotes: 5

Related Questions