【问题标题】:HTML form redirecting to PHP file when submitted?提交时HTML表单重定向到PHP文件?
【发布时间】:2021-04-29 03:58:54
【问题描述】:

我有一个单页网站,里面有一个表格。我试图在填写表格后显示“谢谢”消息来替换“提交”按钮。如果有可能?我希望我的页面是相同的,但带有消息,而不是按钮。 此外,当我单击“提交”时,页面将重定向到 PHP 代码,而不仅仅是显示我想要的消息。有什么可能出错的想法吗?

HTML 表单:

<form action="envia_fale.php" method="post" id="form_" name="form_">
    <input type="text" name="full_name" id="full_name" placeholder="Full Name" required>
    <input type="email" name="email" id="email" placeholder="Email" required>
    <input type="text" name="offer" id="offer" placeholder="Offer" required>
    <input type="submit" id="send" name="send" value="SUBMIT">
</form>

PHP 文件:

<?php 
if(isset($_POST['submit'])){
    $to = "stefanicaguiar1993@gmail.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $full_name = $_POST['full_name'];
    $subject = "OnlyPans.ie form submission";
    $subject2 = "Copy of your form submission";
    $message = "You have received a new offer from " . $full_name . "\n\n" . $_POST['offer'];
    $message2 = "Here is a copy of your message " . $full_name . "\n\n" . $_POST['offer'];

    $headers = "From:" . $from;
    $headers2 = "From:" . $to;
    mail($to,$subject,$message,$headers);
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
    echo "Email sent. Thank you " . $full_name . ", we will contact you shortly.";
    }
?>

【问题讨论】:

  • 您希望页面不会刷新并在 PHP 中发送电子邮件,然后在 HTML 中显示感谢消息?对吗?
  • 如果您想提交表单而不重新加载页面(到您的 PHP 代码),请阅读如何使用 Ajax。这允许您在“后台”(使用 javascript)中提交表单中的数据,然后您可以在收到响应时将按钮替换为您想要的文本。

标签: php html forms


【解决方案1】:

试试这个

<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(function () {
            $('#form_').on('submit', function (e) {
                e.preventDefault();
                $.ajax({
                    type: 'post',
                    url: 'envia_fale.php',
                    data: $('form').serialize(),
                    success: function () {
                        $('#send').replaceWith("<span>Send successfully</span>");
                    },
                    error: function (error) {
                        console.log(error)
                    }
                });
            });
        });
    </script>
</head>

<body>
    <form id="form_" name="form_">
        <input type="text" name="full_name" id="full_name" placeholder="Full Name" required>
        <input type="email" name="email" id="email" placeholder="Email" required>
        <input type="text" name="offer" id="offer" placeholder="Offer" required>
        <input type="submit" id="send" name="send" value="SUBMIT">
    </form>
</body>

</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2016-09-22
    • 2013-09-10
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多