Ferna
Ferna

Reputation: 97

Success Message display on submit html form

I am trying to display a success message just above the submit button, but it’s directing me to a form page. Here it is.

I am trying to:

<!-- The form is on the deck.html page -->
<div class="row footer-newsletter justify-content-center">
    <div class="col-lg-6">
        <form action="forms/subscribe.php" method="post">
            <input type="email" name="email" placeholder="Enter your Email"><input type="submit" value="Subscribe">
        </form>
    </div>

I am getting form inputs on my email, so where am I wrong in the below code?

    // Create email headers
    $headers = 'From: ' . $email_from . "\r\n" .
    'Reply-To: ' . $email_from . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    @mail($email_to, $email_subject, $email_message, $headers);
?>

<!-- include your own success HTML here.

    So I am getting form details to email, but the success
    message below is appearing on /forms/subscribe.php
    where actually I am looking to display just above
    button

-->

    Thank you for contacting us. We will be in touch with you very soon.

<?php

I tried on submit pop up, alert box, but it always took me to the subscribe page and I am looking to display just before the subscribe button.

Here is the image

Upvotes: 2

Views: 29858

Answers (1)

ecrb
ecrb

Reputation: 710

We need to:

  1. Capture and stop the submit event from continuing
  2. Show the message
  3. After some time (let's say 2 seconds), continue the submission.

Check the code below:

We attach an event listener to the form. When the 'submit' event happens, we want to execute our code. The e variable represents the event. We want to stop the event from doing its normal stuff (in this case, send the user to another page), so we say e.preventDefault().

I created a p element with the message on top of the form. This element is hidden by default, but if we add a class show to it, it appears. So, that's what we do. After preventing the event from continuing, we add this class to the message.

Finally, we use the setTimeout() function to count to 2 seconds (2000 ms) and then execute form.submit(), which sends the user to the subscribe page.

const form = document.querySelector('form');
const thankYouMessage = document.querySelector('#thank-you-message');
form.addEventListener('submit', (e) => {
  e.preventDefault();
  thankYouMessage.classList.add('show');
  setTimeout(() => form.submit(), 2000);
});
#thank-you-message {
  display: none;
}

#thank-you-message.show {
  display: block;
}
 <p id="thank-you-message">
   Thank you for contacting us. We will be in touch with you very soon.
 </p>
 <form action="forms/subscribe.php" method="post">
   <input type="email" name="email" placeholder="Enter your Email">
   <input type="submit" value="Subscribe">
 </form>

Upvotes: 8

Related Questions