This question had been asked before that question: Prevent multiple clicks and ActiveForm submission in Yii 2.0.10
Symptoms
I have an active form with id
equals to surasGo
. I attached submit
event using Jquery to handle some tasks before submit. I noticed that any alert
function in the event function is produced twice. I checked out the page HTML source and I found the following snippets:
...
jQuery('#surasGo').yiiActiveForm([], []);
});</script></body>
before the previous snippet there is linked javascript file contains my code:
$('#surasGo').submit(function(e){
e.preventDefault();
suraId = $('#surasId').val()*1;
verseId = $('#versesId').val()*1;
if (!isNaN(verseId*1) && verseId !== 0){
window.location = '/verses/view/'+verseId;
}
else if (!isNaN(suraId) && suraId !== 0){
window.location = '/view/'+suraId;
}
else{
alert(tError+"\n"+tQAccessError);// this alerted twice for example
}
return false;
});
What I have tried
I realized that the first snippet jQuery('#surasGo').yiiActiveForm([], []);
may be responsible for the double invoke of submit events due to active form client validation so I added 'enableClientValidation'=>false
property to the active form:
<?php $form = ActiveForm::begin(['id' => 'surasGo','enableClientValidation'=>false, 'action'...
However, the form is still seems to be undergo to submit event twice! What is the cause of this weird behavior and how to solve it?
I think you also need to stop executing any downstream chain of event handlers. This can be done by calling event.stopImmediatePropagation()
in addition to event.preventDefault().
Try like this :
$('#surasGo').submit(function(e){
e.preventDefault();
e.stopImmediatePropagation(); // this is required in some cases
suraId = $('#surasId').val()*1;
verseId = $('#versesId').val()*1;
if (!isNaN(verseId*1) && verseId !== 0){
window.location = '/verses/view/'+verseId;
}
else if (!isNaN(suraId) && suraId !== 0){
window.location = '/view/'+suraId;
}
else{
alert(tError+"\n"+tQAccessError);// this alerted twice for example
}
return false;
});