Home > Blockchain >  How to add redirect when form is submitted
How to add redirect when form is submitted

Time:03-11

I have been trying to add form submit to my web form, so that it submits data to my email using POST. So far this is what I have and it works perfectly:

<?php 
                            if(isset($_POST['submit'])){
                            $user = $_POST['user'];
                            $phone = $_POST['phone'];
                            $email = $_POST['email'];
 $headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";                         
                          
$to = "your-webmail here";
$subject = "Applied Data";
$txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
$headers = "From: [email protected]" . "\r\n" .
$headers .= 'Cc: [email protected]' . "\r\n";
$ab=(mail($to,$subject,$txt,$headers));
if($ab)
{
  echo"<script>alert('SignUp successfully.')</script>";
  echo "<script>window.open('index.php','_self')</script>";
}
else
{
   echo"Failed";   
}
}
?>

Is there a way to add a redirect to this code, so it redirects after form is submitted?

CodePudding user response:

You have two options (probably more...)

  1. Refactor your code to use AJAX to process the results of the form;
  2. Don't display the headers until you know whether the form has been submitted / processed correctly. A redirect won't work if headers have already been sent.

As you've provided a non-AJAX problem:

<?php 
if(isset($_POST['submit'])){
  $user = $_POST['user'];
  $phone = $_POST['phone'];
  $email = $_POST['email'];
  $headers = "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
  $pageHeaders = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; // etc.
                          
  $to = "your-webmail here";
  $subject = "Applied Data";
  $txt = "Name-'.$user.',<br>Phone -'.$phone.',<br>Email-'.$email.'";
  $headers = "From: [email protected]" . "\r\n" .
  $headers .= 'Cc: [email protected]' . "\r\n";
  $ab=(mail($to,$subject,$txt,$headers));
  if($ab)
  {
    header("Location: index.php");
    die();
  }
  else
    echo $pageHeaders; // You will need to create page headers
    echo"Failed";   
  }
}
?>

This solution doesn't allow for an alert or message to indicate successful save. This could be achieved by redirecting to an interstitial page which can redirect after a timer. See here for an example:

CodePudding user response:

use $_SESSION or $_COOKIE or a flag in your DB/in a temporary file to read & write.

for example:

if (isset($_SESSION['mail_sent']) && $_SESSION['mail_sent'] === true) {
    redirect_to($target_url);
    exit;
}

if(isset($_POST['submit'])) {
    ...
    if (sending was successful) {
        $_SESSION['mail_sent'] === true
    }
    else {
        $_SESSION['mail_sent'] === false
    }
}
  • Related