Hi I’ve been struggling with Ajax, and I sometime don’t understand how it works with Yii.
Basically, I need to use Ajax to send form data to the database.
For now I’m using classic Ajax though I’ve heard Pjax could be used to then render the view element.
Problem is that the form seems to be submitted 2 times.
Here is a simplified code of my view, you’ll notice that I don’t use a model because I need to be able to post this without using a model :
<?php $form = ActiveForm::begin([
'id' => 'comment',
'options' => ['class' => 'form-horizontal'],
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'action' => $route',
]); ?>
<?= Html::errorSummary($comment) ?>
<div class="form-group">
<label class="form-label">Comment form example</label>
<input type="text" name="comment-content">
</div>
<?= Html::submitButton(Yii::t('app', 'Send'), ['class' => 'btn float-right btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php
$this->registerJs("
jQuery(document).ready(function () {
$('#comment').submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
url: $(this).attr('action'),
type: 'post',
data: $(this).serialize(),
success: function(){
alert('ok');
}
});
});
});
")
?>
The error has to come from this page, even if I disable the client or the ajax validation nothing happens. Also I saw some people returning false in their ajax but it causes me to be redirected to the action url (view that doesn’t exist).
My action is a simple Yii::$app->createComment(“INSERT INTO blablabla”);
It works well without Ajax.
For some reason the form is submitted two times with the same data, the alert appears 2 time too.
Here’s a cap of what happens in the network.
If someone know what’s wrong, I could use some help.
Thanks in advance for all answers !