提交表单后停止页面刷新 [英] Stop page refresh after form submit

查看:69
本文介绍了提交表单后停止页面刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了许多其他线程,但看不到我做错了什么,我正在尝试将表单值发送到php文件中,以电子邮件形式发送,但是页面总是刷新.我已经尝试过使用event.preventDefault并在我的ajax调用之前和之后都返回false,但是似乎没有任何效果.我在这里缺少的是我的代码.

I have searched many other threads about this and I can't see what I am doing wrong, I am trying to send form values to a php file to send as an email, however the pages always refreshes. I have tried using event.preventDefault and return false both before and after my ajax call but none seem to work. What am I missing here here is my code.

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");
        }
    }
?>

推荐答案

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

Preventing the default on the submit button should theoretically stop form submission—but:

  1. 输入按钮没有 submit 事件.如果您听 click ,这将起作用,但仅部分原因是因为...
  2. 可能还有其他混杂因素对此造成干扰,即导致表单提交的其他击键或用户交互.
  1. there is no submit event for an input button. If you listen to click, that will work, but only partially because...
  2. there might be other confounding factors that is interfering with this, i.e. other keystrokes or user interactions that causes the form to be submitted.

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

You should be listening to the onsubmit event fired from the form, instead of the event emitted from the submit button. The form's submit event is the definite event that is fired when a form is submitted: be it triggered by <button>, <input type="submit">, or even programatically, such as $form.trigger('submit'). You can give your form an ID, i.e.:

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

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

And then simply perform the exact same logic in the onsubmit callback:

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

    // Rest of the logic
});

如果您无法修改DOM以便可以标识< form> 元素,则使用jQuery的DOM遍历方法也将起作用,即:

If you can't modify the DOM such that you can identify the <form> element, using jQuery's DOM traversal methods will also work, i.e.:

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

    // Rest of the logic
});

为说明我的陈述,即表单的submit事件充当捕获所有提交事件的伞",而不管它们是如何触发的,请参考以下示例:

To illustrate my statement that the form's submit event serves as an "umbrella" that captures all submission events, regardless of how they are triggered, refer to the example I have attached below:

$(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节点上调用 submit()方法,则可以绕过jQuery的 onsubmit 事件处理程序: $('form')[0] .submit().

Note: You can bypass jQuery's onsubmit event handler if you call the submit() method directly on the DOM node: $('form')[0].submit().

这篇关于提交表单后停止页面刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆