How to use PHP to Redirect to another page after form submition?

Hello everyone,
I am trying to add a redirect option to my mail sending code, but it seems not to work. Pls, can someone help me ?

Below is my form:

<!doctype html>
<html class="no-js" lang="fr">
    <form action="mailer.php" class="form-style5 ajax-contact">
        <div class="form-group"><input type="text" name="name" id="name" placeholder="Name"></div>
        <div class="form-group"><input type="text" name="email" id="email" placeholder="e-mail"></div>
        <div class="form-group"><input type="text" name="number" id="number" placeholder="Number"></div>
        <div class="form-group">
            <select name="subject" id="subject"><option hidden disabled>Choose a subject</option>
                <option selected value="Pre-selected value">Subject 1</option>
        <button type="submit" class="vs-btn">Submit</button>
        <p class="form-messages"><span class="sr-only">For message will display here</span></p>

The code contained in the file mailer.php is below.

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
        $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $number = trim($_POST["number"]);
        $subject = trim($_POST["subject"]);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($subject) OR empty($number) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            echo "Plese fill the form.";

        // Set the recipient email address.
        $recipient = "";

        // Set the email subject.
        $subject = "New registration - $subject";

        // Build the email headers.
        $email_headers = "From: $name <$email>\r\n";
        $email_headers .= "MIME-Version: 1.0\r\n";
        $email_headers .= "Content-type: text/html; charset=ISO-8859-1\r\n";
        // Build the email content.
        $email_content = '<html><body>';
        $email_content .= '<table rules="all" style="border-color: #333333;" cellpadding="15px";>';
        $email_content = "<tr style='font-size:14px; margin-bottom:5px;'><td><strong>Name:</strong></td><td> $name</td></tr>";
        $email_content .= "<tr style='font-size:14px; margin-bottom:5px;'><td><strong>Subject:</strong></td><td> $subject</td></tr>";
        $email_content .= "<tr style='font-size:14px; margin-bottom:5px;'><td><strong>E-mail:</strong></td><td> $email</td></tr>";
        $email_content .= "<tr style='font-size:14px; margin-bottom:5px;'><td><strong>Phone:</strong></td><td> $number</td></tr>";
        $email_content .= "</table>";
        $email_content .= "</body></html>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            echo "Thank you for filling in the form. Your registration has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            echo "Oops! A problem occurred and we were unable to submit your registration.";

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        echo "There was a problem with your registration, please try again.";


At the moment, everything works fine, and it displays a success message to the user after he submits the form. But I want to take the users to a different page where I can propose another service to them. So, after submitting the form, they should be redirected to that new page register_success.php .

I tried the code below, but it rather outputs the content of register_success.php on the same form page:

// Send the email. 
if (mail($recipient, $subject, $email_content, $email_headers)) { 
     header("Location: register_success.php");

Just post the files here. I don’t know that too many people are going to open a zip file from a stranger on the internet, no offense intended.


Thank you for posting the files here.
I am a new user, so I am not yet allowed to post attachments, that is why I used a Google Drive link. Sorry about that.

money on the problem being solved by:

You can only send header() calls before any output to the screen is made. That includes any code or empty lines before the <?php.`

(No, i’m not downloading files from a random person on the forum. You should be able to put your form code into a code block here by putting triple-backticks (```) before and after the code block.


Thank you @m_hutley
I have edited my question, and added my code to the post. Kindly take a look at it, and guide me to the right direction.
For the meantime, I will try your suggestion and will post back in case I get it working.

1 Like

You do have the opening tag: <?php at the very top of register_success.php?

Yes i do have the opening php tag.

For now, the content of register_success.php is just an echo. I am yet to build it up.
The code of the page following :


    echo "Content of success registration to be coded here";

If it got the output from register_success.php, it worked. It redirected the user’s browser. What part do you think failed?

There is no fail, but it does not work the way I expect it to.
Right now, upon clicking the submit button, I see Content of success registration to be coded here displaying below the form. Which is not what I expect.

I want it to take the user to the newly created page register_success.php, not display its content below the form.

The page register_success.php will hold the code for advertising a pdf book. So it will not be neat to show it below the form after submission. The best is to do it on a separate page.

is something binding to the form’s onsubmit event that is making the form submit via AJAX? This doesnt sound like a PHP problem, it sounds like a Javascript form handler is doing something.

Well, i used some js script and css for better output. Maybe I should share it here :

Google Fonts
============================== -->
<link rel="preconnect" href="">
<link rel="preconnect" href="" crossorigin>
<link href=";500;700&display=swap" rel="stylesheet">

All CSS File
============================== -->
<!-- Bootstrap -->
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<!-- <link rel="stylesheet" href="assets/css/app.min.css"> -->
<!-- Fontawesome Icon -->
<link rel="stylesheet" href="assets/css/fontawesome.min.css">
<!-- Magnific Popup -->
<link rel="stylesheet" href="assets/css/magnific-popup.min.css">
<!-- Slick Slider -->
<link rel="stylesheet" href="assets/css/slick.min.css">
<!-- Theme Custom CSS -->
<link rel="stylesheet" href="assets/css/style.css">

All Js File
============================== -->
<!-- Jquery -->
<script src="assets/js/vendor/jquery-3.6.0.min.js"></script>
<!-- Slick Slider -->
<script src="assets/js/slick.min.js"></script>
<!-- <script src="assets/js/app.min.js"></script> -->
<!-- Bootstrap -->
<script src="assets/js/bootstrap.min.js"></script>
<!-- Wow.js Animation -->
<script src="assets/js/wow.min.js"></script>
<!-- Magnific Popup -->
<script src="assets/js/jquery.magnific-popup.min.js"></script>
<!-- Main Js File -->
<script src="assets/js/main.js"></script>

I also have this piece of code to go to the previous page

<div class="container z-index-common">
    <ul class="breadcumb-menu">
		<li><a href="javascript:history.back()">Accueil</a></li>

The for action is set as follows :
<form action="mailer.php" class="form-style5 ajax-contact">
and the submit even is as follows :
<button type="submit" class="vs-btn">Submit</button>

I just found a file (main.js) among the js files I used. It contains the following Ajax code. Do you think this handles the form submit event ? If yes, could you pls help me add the redirect to it ?

/*----------- 08. Ajax Contact Form ----------*/
var form = '.ajax-contact';
var invalidCls = 'is-invalid';
var $email = '[name="email"]';
var $validation = '[name="name"],[name="email"],[name="number"],[name="subject"],[name="callchoice"],[name="message"]'; // Must be use (,) without any space
var formMessages = $(form).find('.form-messages');

function sendContact() {
var formData = $(form).serialize();
var valid;
valid = validateContact();
if (valid) {
url: $(form).attr('action'),
data: formData,
type: "POST"
.done(function (response) {
// Make sure that the formMessages div has the 'success' class.
// Set the message text.
// Clear the form.
$(form + ' input:not([type="submit"]),' + form + ' textarea').val('');
.fail(function (data) {
// Make sure that the formMessages div has the 'error' class.
// Set the message text.
if (data.responseText !== '') {
} else {
formMessages.html('Oops! An error occured and your message could not be sent.');

Happy to help with the redirect in your mail sending code!

There are two common approaches depending on your setup:

  1. Server-side redirect: If you’re using a server-side scripting language (like PHP, Python, Node.js), you can configure a redirect after sending the email. This is typically done using HTTP headers.
  2. HTML redirect in email content: If you’re including a link in the email body itself, you can add an HTML <a> tag with a href attribute pointing to the redirect URL.

Let me know which approach you’re using, and I can provide more specific guidance!

1 Like

Yes, this is the Ajax code that submits the form.

1 Like

its the ajax that submits the form, but its not the binder… i expect the binder to be preventDefaulting the form submission… eh.

after the set line on valid (so before the if), return valid; and see if that works.

Since i am using php, i believe the server-side redirect approach is convenient.

With that said, kindly note that i have already tried the following code, which was unsuccessful.

// Send the email. 
if (mail($recipient, $subject, $email_content, $email_headers)) { 
     header("Location: register_success.php");

I will be happy to get more help and guidance from you, to find a working solution.

You can’t do the redirect from within the form-handling PHP code when that code is called using Ajax. An Ajax call captures all the echoed output from the PHP code and returns it, where your JS code then displays it in the form. One of the main reasons for submitting via Ajax is that the screen doesn’t refresh itself on a form submit.