-1

This php code emails the form contents to the intended recipient. I would think that I could shoehorn in some form post-processing (js page redirects, perhaps) in the script below. Like after "DO SOMETHING AFTER FORM SUBMISSION". I tried this and it worked!

  <!-- (B) AJAX SUBMISSION -->
  <script>
  function doajax () {
   // (B1) GET FORM DATA
   var data = new FormData(document.getElementById("cform"));
   // REQUIRED: APPEND CAPTCHA RESPONSE
   data.append("g-recaptcha-response", grecaptcha.getResponse());

   // (B2) AJAX FETCH
   fetch("process.php", { method: "POST", body: data })
.then((res) => { alert ('message sent'); window.location.href = "index.php"; })

   });
   return false;
  }
  </script>

HTML:

<form id="cform" method="post" onsubmit="return doajax();">
<input type="text" name="name" required/>
<input type="email" name="email" required/>
<textarea name="message" required></textarea>

<div class="g-recaptcha" data-sitekey="--- SITE KEY ---></div>

<input type="submit" id = "submit" value="Submit"/>
</form>

process.php

<?php
// (B) VERIFY CAPTCHA 
$secret = "---google recaptcha secret ---"; 
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=".$_POST["g-recaptcha-response"];
$verify = json_decode(file_get_contents($url));
if (!$verify->success) { $error = "Invalid captcha"; }

// (C) SEND MAIL
 $mailTo = "me@gmail.com"; 
 $mailSubject = "Contact Form";
 $mailBody = "";
 
 foreach ($_POST as $k=>$v) {
 if ($k!="g-recaptcha-response") { $mailBody .= "$k: $v\r\n"; }
 }

 if (!@mail($mailTo, $mailSubject, $mailBody)) { $error = "Failed to send mail";}
?>
verlager
  • 794
  • 5
  • 25
  • 43

1 Answers1

-1

Instead of writing code to the browser like you've included:

echo "<script>alert('Successfully sent'); window.location = './index.php';</script>";
exit;

Try replacing the above with PHP to do the redirect by setting the header:

header('Location: https://www.google.com');

Note that this requires there be no output previously on the page as the header can't be set after HTML output begins.

For more information on redirects in PHP, check out this answer: How do I make a redirect in PHP?

verl
  • 116
  • 3
  • I followed your lead but the page didn't redirect. – verlager Jul 10 '22 at 03:41
  • Did you get an error? What happens if you remove all the mailing code and just have the redirect. Does it work? If so, can you slowly add your code back in to see what breaks it? It's possible something is throwing an error onto the screen previously, preventing the header from redirecting. – verl Jul 10 '22 at 03:53
  • To help with debugging you can also try adding this to the top of your script which will suppress all errors: `error_reporting(0); ini_set('display_errors', 0);` – verl Jul 10 '22 at 03:54
  • I solved it. Not very pretty but jshint may remedy that. – verlager Jul 10 '22 at 05:30