Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind to beforeSubmit event on an AJAX-loaded form in Yii?

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.

like image 955
Chloe Avatar asked Dec 06 '25 14:12

Chloe


1 Answers

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:

  1. make sure the registered JS is part of the response, which should be the case if you render the view with renderAjax() in the controller.
  2. Javascript contained in the response is executed. According to the JQuery documentation this is the case for an ajax request, if dataType setting is set to html:

    "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

like image 75
cebe Avatar answered Dec 08 '25 06:12

cebe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!