I have a form that I load dynamically via AJAX. I try to bind beforeSubmit on the form, but it seems to fail as the form is submitting and the browser is loading a new page. When the form was static in the page, the beforeSubmit event handler was working and the browser did not change location. I tried to change from $('#emailForm').on('beforeSubmit', function(event) { to below but it didn't work. How do I attach beforeSubmit on the form?
view
<div id="emailBody"><!-- Placeholder for email form w/CAPTCHA --></div>
<?#= $this->render('_email_form.php', ['emailModel' => new EmailModel()]) ?>
partial
<?php $form = ActiveForm::begin(['id' => 'emailForm', 'action' => 'send-email', 'method' => 'post', 'enableAjaxValidation' => false, 'options' => ['class' => '']]) ?>
<?= $form->field($emailModel, 'fromName') ?>
JavaScript
jQuery(function() {
$('#emailModal').on('show.bs.modal', function (event) { // load email form w/CAPTCHA
$('#emailBody').load('email-form');
});
$('#emailBody').on('beforeSubmit', '#emailForm', function(event) {
event.preventDefault();
rendered HTML
<div id="emailBody"><form id="emailForm" class="" action="send-email" method="post">
<input type="hidden" name="_csrf" value="aS1LcTJfeU4tXHkuQG4yCjYbDCMfLTEMLEB4EwY4TygGaAAJdBNMPw==">
Not that it's relevant, I'm using PHP, Bootstrap, and Yii framework.
ActiveForm generates the javascript needed to initialize it here: https://github.com/yiisoft/yii2/blob/49aec24ae1f01d51b4f3cec8e44d44387022d06b/framework/widgets/ActiveForm.php#L201-L206
For this Javascript code to be executed on the client side, you have to ensure the following:
dataType setting is set to html:
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With