Joshi
Joshi

Reputation: 2790

yii2 form AJAX to different action url

I am not able to make it work: also it is always redirecting to `action/create' whereas i want to not to redirect to that action.

my code is like this in footer view:

<script>

    jQuery(document).ready(function($) {
$("#quick-contact").on('submit',function(event) {
//  $("#quick-contact").on('beforeSubmit',function(event) {


        event.preventDefault(); // stopping submitting
        console.log("step1");
        var form = $(this);
        var formData = form.serialize();
      //  var data = $(this).serializeArray();
        var url = $(this).attr('/quick-contact/create');

        $.ajax({
            url: form.attr("action"),
            type: form.attr("method"),
            dataType: 'json',
            data: formData

        })

        .done(function(response) {
            if (response.data.success == true) {
                alert("Wow you commented");
            }
        })
        .fail(function() {
            console.log("error");
        });
      //  return false;
    });
}); 
    </script>
<?php //pjax::begin(['enablePushState' => false]); ?>
<div id="contact-form">    

    <?php $form = ActiveForm::begin(['action'=>'/quick-contact/create','id'=>'quick-contact','method'=>'post']); ?>

<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'message')->textarea(['rows' => 2]) ?>

<div class="form-group">
    <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>

<?php ActiveForm::end(); ?>
</div>


    <div id="quick-contact-form">
<?php if (Yii::$app->session->hasFlash('success')): ?>
<div class="alert alert-success alert-dismissable">
     <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
     <h4><i class="icon fa fa-check"></i>Saved!</h4>
     <?= Yii::$app->session->getFlash('success') ?>
</div>
<?php endif; ?>

// display error message
<?php if (Yii::$app->session->hasFlash('error')): ?>
<div class="alert alert-danger alert-dismissable">
     <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
     <h4><i class="icon fa fa-check"></i>Saved!</h4>
     <?= Yii::$app->session->getFlash('error') ?>
</div>
<?php endif; ?>
            </div></div>
            <?php // pjax::end(); ?>

and in controller action like:

public function actionCreate()
    {
        $model = new QuickContact();
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            var_dump($_POST);
            if ($model->load(Yii::$app->requset->post()) && $model->save()) {            

                Yii::$app->session->setFlash('success','Thanks We will get in touch with you');

            // $st = Yii::$app->getTable;
              //      $email_template = $st->email_template(1);
            Yii::$app->mailer->compose()
                ->setTo('[email protected]')
                ->setFrom(['[email protected]'])
                ->setSubject('QuickContact')
                ->setHtmlBody('Request from - '.$model->name.'<br>'.'Email - '.$model->email. '<br>'.'Message - '.$model->message) 
                ->send();

                      /*  Yii::$app->mailer->compose('template', ['id' => 1, 'email_template' => $email_template,   'sender_name'=>$model->name,'message'=>$model->address])

                ->setTo($this->email)
                ->setFrom([$email => "vedic"])
                ->setSubject($this->subject)
                //->setHtmlBody('Hi '.$this->name.'<br>'.'Welcome to Nexgen'.'<br>'.'We confirm of having received your Enquiry/feedback as below'.'<br>'.$this->body )
                ->send();
                                */
            }else{
                Yii::$app->session->setFlash('error','There was an error in submission.');
            }
            //return $this->render('/site/index');

            }

           // return $this->renderPartial('/site/index');

    }

updated jquery script code:

Now ajax request is going through, but the response I am getting is like:

name Unknown Property message Getting unknown property: yii\web\Application::requset code 0 type yii\base\UnknownPropertyException file /var/www/clients/client2/web238/web/vendor/yiisoft/yii2/base/Component.php

Upvotes: 0

Views: 2118

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23788

just replace the

$("#quick-contact").submit(function(event) {

with

$("#quick-contact").on('beforeSubmit',function(event) {

Update

The reason you are getting the error is because you have several errors in your console regarding the 3rd party scripts, and until unless you remove them you wont be able to get it working, you need to fix the following

enter image description here

Another thing that is missing is the return false; statement in your beforeSubmit event you should add this line after the ajax call, to prevent form submission.

$("#quick-contact").on('beforeSubmit',function(event) {

    //....your code for ajax call

    return false;
});

Update 2

The reason for the error is the spelling for the requset which should be rather request you need to change the line

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

to

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

if you still into problems please add a separate question as this question addresses the ajax part only which is solved already.

Upvotes: 1

Related Questions