开发者问题收集

AJAX 调用后刷新表单

2022-09-30
98

背景

我的网站上有一个电子邮件注册表单。

该表单出现在每个网页的两个区域:页眉和页脚

它是完全相同的表单,只是出现在页面的顶部和底部,以获得更好的用户体验和可访问性。

该表单使用 jQuery/AJAX 脚本向用户提供成功和错误响应。 (即,“成功!您的订阅已完成。”和“错误。请检查并重新提交”)

当用户提交表单时,用户输入将添加到数据库,并向站点管理员发送通知电子邮件。

如果使用页眉表单,则电子邮件主题为“已添加电子邮件订阅者(页眉表单)”。

如果使用页脚表单,则主题为“已添加电子邮件订阅者(页脚表单)”。

(这只是一种让管理员衡量每种表单使用情况的简单技术。)

以下是 PHP 的样子:

if ( $form_selected == 'header' ) {
    
        $mail->Subject = 'Email Subscriber Added (Header Form)';
        $mail->Body = $message;

} elseif ( $form_selected == 'footer' ) {
    
        $mail->Subject = 'Email Subscriber Added (Footer Form)';
        $mail->Body = $message;

} else {

        $mail->Subject = 'Email Subscriber Added (form version unknown)';
        $mail->Body = $message; 

}

到目前为止,一切正常。


问题

问题是,如果站点用户在同一会话中提交多个电子邮件订阅,则站点管理员会获得上述 PHP 脚本中的 else 版本(“表单版本未知”)。在正常会话期间,永远不应调用此选项。但在再次考虑 ifelseif 选项之前,需要刷新页面。


问题

有没有办法在 jQuery/AJAX 脚本中解决此问题(见下文)?如果有必要,我也愿意修改 PHP。

$(function() {

  // set up event listener
  $('#header-form, #footer-form').submit(function(e) {
    // disable html submit button
    e.preventDefault();

    // get the submit button
    var submitButton = $('[type=submit]', this);

    // get the messages element
    var formResponses = $('#header-form-responses, #footer-form-responses', this);
    formResponses.text(" ");

    // serialize form data
    var formData = $(this).serialize();

    // disable submit button to prevent unnecessary submission
    submitButton.attr('disabled', 'disabled');

    // tell users that form is sending
    submitButton.text('Processing...');

    // submit form via AJAX
    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data: formData
      })

      .done(function(response) {
        // make sure formResponses element has 'success' class
        $(formResponses).removeClass('error');
        $(formResponses).addClass('success');

        // set message text
        $(formResponses).text('Your subscription is complete. Thank you!');

        // clear form
        $('input').val('');
      })

      .fail(function(data) {
        // make sure formResponses element has 'error' class
        $(formResponses).removeClass('success');
        $(formResponses).addClass('error');

        // set the message text
        $(formResponses).text('Input error. Please review and re-submit.');
      })

      .always(function(data) { // this will always fire even if the request fails
        submitButton.removeAttr('disabled');
        submitButton.text('Send');
      });

  });

});
<!-- simplified HTML -->

<form action="process_form.php" method="post" id="header-form">
  <input type="email" name="email_subscription">
  <input type="hidden" name="formtarget" value="header">
  <button type="submit" name="submit_subscription">Submit (Header)</button>
  <p id="header-form-responses"></p>
</form>

<form action="process_form.php" method="post" id="footer-form">
  <input type="email" name="email_subscription">
  <input type="hidden" name="formtarget" value="footer">
  <button type="submit" name="submit_subscription">Submit (Footer)</button>
  <p id="footer-form-responses"></p>
</form>
2个回答

如果其中包含触发 PHP if 条件的数据:

<input type="hidden" name="formtarget" value="header">

则这将明确清除该数据:

// clear form
$('input').val('');

相反,只清除您想要清除的字段:

// clear form
$('input[type="email"]').val('');
David
2022-09-30

使用 $('input:not([type="hidden"])').val('') 排除隐藏输入。您的 JS 正在清除所有输入,包括您的隐藏输入。

$(function() {

  // set up event listener
  $('#header-form, #footer-form').submit(function(e) {
    // disable html submit button
    e.preventDefault();

    // get the submit button
    var submitButton = $('[type=submit]', this);

    // get the messages element
    var formResponses = $('#header-form-responses, #footer-form-responses', this);
    formResponses.text(" ");

    // serialize form data
    var formData = $(this).serialize();

    // disable submit button to prevent unnecessary submission
    submitButton.attr('disabled', 'disabled');

    // tell users that form is sending
    submitButton.text('Processing...');

    // submit form via AJAX
    $.ajax({
        type: 'POST',
        url: $(this).attr('action'),
        data: formData
      })

      .done(function(response) {
        // make sure formResponses element has 'success' class
        $(formResponses).removeClass('error');
        $(formResponses).addClass('success');

        // set message text
        $(formResponses).text('Your subscription is complete. Thank you!');

        // clear form except hidden inputs
        $('input:not([type="hidden"])').val('')
      })

      .fail(function(data) {
        // make sure formResponses element has 'error' class
        $(formResponses).removeClass('success');
        $(formResponses).addClass('error');

        // set the message text
        $(formResponses).text('Input error. Please review and re-submit.');
      })

      .always(function(data) { // this will always fire even if the request fails
        submitButton.removeAttr('disabled');
        submitButton.text('Send');
      });

  });

});
<!-- simplified HTML -->

<form action="process_form.php" method="post" id="header-form">
  <input type="email" name="email_subscription">
  <input type="hidden" name="formtarget" value="header">
  <button type="submit" name="submit_subscription">Submit (Header)</button>
  <p id="header-form-responses"></p>
</form>

<form action="process_form.php" method="post" id="footer-form">
  <input type="email" name="email_subscription">
  <input type="hidden" name="formtarget" value="footer">
  <button type="submit" name="submit_subscription">Submit (Footer)</button>
  <p id="footer-form-responses"></p>
</form>
spac3man
2022-09-30