Stef
Stef

Reputation: 11

HTML form redirecting to PHP file when submitted?

I have an one-page website with a form in it. I am trying to show a "Thank you" message to replace the button "submit" after the form is filled. If that is possible? I want my page to be the same, but with the message, instead of the button. Also, when I click "submit" the page is redirect to the PHP code, instead of just showing the message I want. Any ideas of what could be wrong?

HTML form:

<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 file:

<?php 
if(isset($_POST['submit'])){
    $to = "[email protected]"; // 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.";
    }
?>

Upvotes: 1

Views: 111

Answers (1)

Soufiene Slimi
Soufiene Slimi

Reputation: 119

Try this out

<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>

Upvotes: 1

Related Questions