sms
sms

Reputation: 103

yii2 ajax form dose not work new here in yii

This is yii2 form and ajax script which is dose not working any one know how to add ajax to submit form am new here in yii2 please help me wondering here

<script>
    $("#frmDemo").submit(function (e) 
    {
        e.preventDefault()
        alert('hello');
        return false;
        var user_fname = $("#usermastermodel-user_fname").val();
        var user_lname = $("#usermastermodel-user_lname").val();
        var user_mobile = $('#usermastermodel-user_mobile').val();
        if (user_fname == "" || user_lname == "" || user_mobile == "")
        {
            $("#error_message").show().html("All Fields are Required");
        } else {
            $("#error_message").html("").hide();
            $.ajax({
                type: "POST",
                url: "actionCreate",
                data: {user_fname: user_fname, user_lname: user_lname, user_mobile: user_mobile},
                success: function (data) {
                    $('#success_message').fadeIn().html(data);
                    setTimeout(function () {
                        $('#success_message').fadeOut("slow");
                    }, 2000);
                }
            });
        }
    })
</script>

This is my form which having name mobile number need to submit this form into db

<?php
$js = Yii::$app->homeUrl . './usermaster/js/jquery-2.1.4.min.js';
$this->registerJsFile($js, ['depends' => yii\web\JqueryAsset::className()]);
?>
<div class="usermaster-model-form">

    <?php $form = ActiveForm::begin(['id' => 'frmDemo']); ?>

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

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

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

    <div class="form-group">
        <?= Html::Button($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

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

</div>

Upvotes: 0

Views: 131

Answers (1)

Nitin Pund
Nitin Pund

Reputation: 1092

To use ajax, syntax is as follows. you can modify your code accordingly. Observe the url pattern carefully, its controller/action. Also you must register js using $this->registerJs();

$.ajax({
        type     :'POST',
        cache    : false,
        url      : '" . yii\helpers\Url::to(["/controller/action"]) . "',
        data: {user_fname: user_fname, user_lname: user_lname, user_mobile: user_mobile},
        success  : function(response) {
           // process your response here
        }
    });
    return false;

Upvotes: 1

Related Questions