表单提交后停止页面刷新

Stop page refresh after form submit

我已经搜索了很多关于此的其他主题,但我看不出我做错了什么,我正在尝试将表单值发送到 php 文件以作为电子邮件发送,但是页面总是刷新。我曾尝试在 ajax 调用前后使用 event.preventDefault 和 return false,但 none 似乎有效。我在这里缺少的是我的代码。

HTML

<form method="post" name="registerForm" class="form">
    <label for="fullName" class="form__fullname form__label">Full Name</label>

    <input type="text" name="fullName" placeholder="Richard Thomson" maxlength="40" tabindex="1" pattern="^[a-zA-Z\s]*$" class="form__input" id="name" required>

    <label for="email" class="form__email form__label">Email</label>

    <input type="email" name="email"  placeholder="richard.thomson45@gmail.com" tabindex="2" class="form__input" id="email" required>

    <label for="telephone" class="form__tel form__label">Phone</label>

    <input type="tel" name="telephone" placeholder="07915834998" tabindex="3" pattern="[0-9]{11}" maxlength="11" class="form__input" id="telephone" required>

    <input type="submit" value="Submit" name="submit" class="form__submit" id="submit">
</form>

JS

var fullName,
    telephone,
    email,
    submitButton = $("#submit"),        
    formData;

submitButton.submit(function (event) {
    // event.preventDefault();

    fullName = $("#name").val();
    telephone = $("#telephone").val();
    email = $("#email").val();
    formData = {
        'name': fullName,
        'email': email,
        'telephone': telephone
    };

    $.ajax({
            type: 'POST',
            url: 'email.php',
            data: formData,
            dataType: 'json'
        })
        .done(function (data) {
            console.log(data);
        })
        .fail(function () {
            console.log("not working");
        });

    return false;
});

PHP

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['telephone'])) {

            if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $email = $_POST['email'];
            }

            if (preg_match("/^[a-zA-Z\s]*$/", $_POST['fullName'])) {
                $fullName = $_POST['fullName'];
            }

            if (preg_match("/[0-9]{11}/", $_POST['telephone'])) {
                $telephone = $_POST['telephone'];
            }

            $telephone = substr_replace(substr_replace($telephone," ",3,0)," ",8,0);

            $emailTo = "test@hotmail.co.uk";
            $emailFrom = "contact@test.co.uk";
            $subject = "I would like to know more about test";
            $message = "Name:" . " " . $fullName . "\r\n\r\n";
            $message .= "Email:" . " " . $email . "\r\n\r\n";
            $message .= "Telephone:" . " " . $telephone;

            $headers = "From: $emailFrom \r\n";
            $headers .= 'Content-Type: text/plain; charset=utf-8'; 
            $headers .= "Reply-To: $email \r\n";

            $success = mail($emailTo, $subject, $message, $headers);

        } else {
            echo("Please fill all necessary fields");
        }
    }
?>

防止提交按钮上的默认设置理论上应该会停止表单提交——但是:

  1. 输入按钮没有 submit 事件。如果你听 click,那会奏效,但只是部分因为...
  2. 可能有其他混杂因素干扰了这一点,即导致提交表单的其他击键或用户交互。

您应该监听从表单触发的 onsubmit 事件,而不是从提交按钮发出的事件。表单的提交事件是提交表单时触发的确定事件:由 <button><input type="submit"> 或什至以编程方式触发,例如 $form.trigger('submit')。你可以给你的表单一个 ID,即:

<form method="post" name="registerForm" class="form" id="registrationForm">

然后在 onsubmit 回调中简单地执行完全相同的逻辑:

$('#registrationForm').on('submit', function(e) {
    // Prevent form submission by the browser
    e.preventDefault();

    // Rest of the logic
});

如果您无法修改 DOM 以识别 <form> 元素,使用 jQuery 的 DOM 遍历方法也可以,即:

var $form = submitButton.closest('form');
$form.on('submit', function(e) {
    // Prevent form submission by the browser
    e.preventDefault();

    // Rest of the logic
});

为了说明我的声明,即表单的提交事件用作捕获所有提交事件的 "umbrella",无论它们是如何触发的,请参阅我在下面附加的示例:

$(function() {
  $('#form').on('submit', function(e) {
    console.log('Form submission captured. It is triggered by: ', document.activeElement);
    //e.preventDefault();
  });
  
  $('#submitInput').on('submit', function(e) {
    console.log('Triggering submit event from <input>');
  });
  
  $('#submitButton').on('click', function() {
    console.log('Triggering submit event from <button type="submit" />');
  });

  $('#submitProgramatically').on('click', function() {
    console.log('Triggering submit event using JS only');
    $('#form').trigger('submit');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" action="#">
  <input type="text" placeholder="Just another text field" />
  <br />
  <input type="submit" value="Submit using an <input>" id="submitInput" />
  <br />
  <button id="submitButton">Submit using a &lt;button&gt;</button>
  <br />
  <a href="#" id="submitProgramatically">Submit programatically using JS</a>
</form>

注意:如果直接在 DOM 节点 $('form')[0].submit() 上调用 submit() 方法,则可以绕过 jQuery 的 onsubmit 事件处理程序。