简体   繁体   中英

How can I prevent page from reloading after PHP form submssion?

I have this basic PHP form and I'd like to prevent the page from refreshing after pressing the submit button. Or more like, I would like to have a confirmation paragraph created after the form is sent.

I'm very close, but the paragraph is not getting displayed I think because the page is getting refreshed.

if($_POST["submit"]) {
$recipient="contact@d.com";
$subject="Form to email message";
$sender=$_POST["sender"];
$senderEmail=$_POST["senderEmail"];
$message=$_POST["message"];

$mailBody="Name: $sender\nEmail: $senderEmail\n\n$message";

mail($recipient, $subject, $mailBody, "From: $sender <$senderEmail>");

$thankYou="<div class='thanksDiv'><p>Thank you! Your message has been sent. I'll get back to you ASAP. <i class='as fa-smile-beam'></i></p><a style='cursor:pointer' class='thanksExit'><i class='fas fa-times fa-2x'></i></a></div>";
}

 <form id="myForm" name="myemailform" method="post" action="index.php"> <div class="inline"> <label>Name</label> <input id="firstName" required placeholder="eg: Emma" type="text" size="32" name="sender" value=""> </div> <div class="inline"> <label>Email</label> <input autocomplete="off" required id="email" type="email" placeholder="eg: EmmaSmith@example.com" name="senderEmail"> </div> <div class="inline"> <label>How can I help?</label> <textarea id="textarea" required placeholder="Type a message here..." name="message"></textarea> </div> <input type="submit" name="submit" value="Submit"> <?=$thankYou?> </form>

Note: I've tried the preventDefault function and Ajax and they didn't work.

Thank you!

They are different ways and approaches to resolve that issue.

How I do it: I have a processing php that will receive the post and send the email then I redirect the user to a thanks page.

header("location: thanks.php);
exit();

You can also use ajax, and disable the button once it is pressed. It depends on the developer, framework and programming preferences.

You will first need to send some data back to your AJAX from PHP.

session_start();
if(isset($_POST["submit"])) {
  $recipient="contact@d.com";
  $subject="Form to email message";
  $sender=$_POST["sender"];
  $senderEmail=$_POST["senderEmail"];
  $message=$_POST["message"];

  $mailBody="Name: $sender\nEmail: $senderEmail\n\n$message";

  mail($recipient, $subject, $mailBody, "From: $sender <$senderEmail>");

  $thankYou="<div class='thanksDiv'><p>Thank you! Your message has been sent. I'll get back to you ASAP. <i class='as fa-smile-beam'></i></p><a style='cursor:pointer' class='thanksExit'><i class='fas fa-times fa-2x'></i></a></div>";
    
  echo $thankYou;
}

Now your PHP will send the HTML back to the AJAX Call.

 $(function() { $("#myForm").submit(function(e) { e.preventDefault(); $.post($(this).attr("action"), $(this).serialize(), function(result) { $(this).append(result); }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="myForm" name="myemailform" method="post" action="index.php"> <div class="inline"> <label>Name</label> <input id="firstName" required placeholder="eg: Emma" type="text" size="32" name="sender" value=""> </div> <div class="inline"> <label>Email</label> <input autocomplete="off" required id="email" type="email" placeholder="eg: EmmaSmith@example.com" name="senderEmail"> </div> <div class="inline"> <label>How can I help?</label> <textarea id="textarea" required placeholder="Type a message here..." name="message"></textarea> </div> <input type="submit" name="submit" value="Submit"> </form>

In this JavaScript, you will notice, I make use of the Event object for the Submit Callback. This allows me to use .preventDefault() properly.

Trying to put the message into your Session is fine, yet it requires loading another page to call up a session. PHP is only executed before the web server sends the HTML to the Web Browser. With AJAX, the Post request is being performed "in the background", so data can be sent back in HTML, Text, JSON, or XML without the need to reload or redirect. The JavaScript can then work with that data on the same page, no "flicker".

In this case, we append the HTML to the Form, so once the message has been sent via PHP mail() , the User will see the Thank You message.

Update

Consider the following PHP alternate code.

<?php
if(isset($_POST["submit"])) {
  $recipient = "contact@d.com";
  $subject = "Form to email message";
  $sender = $_POST["sender"];
  $senderEmail = $_POST["senderEmail"];
  $message = wordwrap($_POST["message"], 70, "\r\n");
  $headers = "From: $sender <$senderEmail>\r\n";
  $headers .= "Reply-To: $senderEmail\r\n";
  $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
  $headers .= "X-Originating-IP: " . $_SERVER['REMOTE_ADDR']

  $mailBody="Name: $sender\r\nEmail: $senderEmail\r\n\r\n$message";

  var $res = mail($recipient, $subject, $mailBody, $headers);

  if($res){
    echo "<div class='thanksDiv'><p>Thank you! Your message has been sent. I'll get back to you ASAP. <i class='as fa-smile-beam'></i></p><a style='cursor:pointer' class='thanksExit'><i class='fas fa-times fa-2x'></i></a></div>";
  } else {
    echo "<div class='mailError'><p>Sorry, there was an error sending your message. Please check the details and try submitting it again.</p></div>";
  }
}

Some solutions:

If the user does not need to stay on the same page then as Vidal posted , redirect to a success/thank you page.

If the user needs to stay on the same page then you have a few options:

Method A:

  1. Set session with a form identifier (anything) if nothing is posted (ie initial page load). eg if(.isset($_POST['field'])){ $_SESSION['....
  2. When form is submitted, check that session exists with the form identifier and process then destroy session.
  3. Now if it's refreshed, the session won't exist, you can inform user that it's already submitted

Problem with this is that if session has timed out and the refresh is done, it will go through.

Method B:

Disable refresh: https://stackoverflow.com/a/7997282/1384889

Method C:

Check database for repeat entry

Method D: (I don't like this but it's used plenty)

Reload same page with '&t='.time() appended to URL by php header() or javascript depending on where your script is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM