Ezybusy Posted June 2 Share Posted June 2 (edited) 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 ? I tried to add a redirect using header("Location: thanks.php"); but it does not work. Form and mail sending files are attached below https://drive.google.com/file/d/1uA_wt8Ztofs0RHLZpensO8XjqeQuoDta/view?usp=sharing Edited June 2 by Ezybusy provide more details Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/ Share on other sites More sharing options...
Barand Posted June 2 Share Posted June 2 Safe browsing dictates never to accept links from strangers, so please post code (in a code block using <> button). The usual reason for a header () to fail is because output has already been sent to the browser (even if it is only whitespace) at the time of the call. Check this is not the case. Also make sure you call exit() after the call so there is no unwanted subsequent processing of the page. If the above is the reason you should have received an error message - do you have error reporting ON? Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1626588 Share on other sites More sharing options...
Ezybusy Posted June 2 Author Share Posted June 2 3 hours ago, Barand said: Safe browsing dictates never to accept links from strangers, so please post code (in a code block using <> button). The usual reason for a header () to fail is because output has already been sent to the browser (even if it is only whitespace) at the time of the call. Check this is not the case. Also make sure you call exit() after the call so there is no unwanted subsequent processing of the page. If the above is the reason you should have received an error message - do you have error reporting ON? I am sorry. Below is my code I am trying to add a redirect option to my mail sending code, but it seems not to work. Pls, can someone help me ? My form is as follows: <!doctype html> <html class="no-js" lang="fr"> <head> <body> <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> </select> </div> <button type="submit" class="vs-btn">Submit</button> <p class="form-messages"><span class="sr-only">For message will display here</span></p> </form> </body> </html> The code contained in the file mailer.php is below. <?php // 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. http_response_code(400); echo "Plese fill the form."; exit; } // Set the recipient email address. $recipient = "mymail@gmail.com"; // 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. http_response_code(200); echo "Thank you for filling in the form. Your registration has been sent."; } else { // Set a 500 (internal server error) response code. http_response_code(500); echo "Oops! A problem occurred and we were unable to submit your registration."; } } else { // Not a POST request, set a 403 (forbidden) response code. http_response_code(403); 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 under the form after clicking the submit button : // Send the email. if (mail($recipient, $subject, $email_content, $email_headers)) { header("Location: register_success.php"); Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1626613 Share on other sites More sharing options...
gizmola Posted June 2 Share Posted June 2 The code you added looks correct. First off, remove the end tag from your script. This is the final "?>" Also after the header call, add a line with "exit;" When you are testing this code, make sure you have your developer tools open, and you are looking at an emptied network tab when you submit the form. This will allow you to see what is going on when you submit the form, and you'll be able to look at the response. Any sort of error or message will interfere with the redirect in the HTTP header of the response, so this will help you debug that. Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1626626 Share on other sites More sharing options...
gizmola Posted June 2 Share Posted June 2 One other thing I noticed is that you are going a bit crazy with your use of response codes. A 200 code will be sent automatically, and you should not be sending all these other responses unless this is a REST api, where a client is doing something with the responses. In this case, it appears you are just returning some information on an otherwise blank page. Typically people creating a feature like this will integrate the form with the submission (a self posting form) and display errors back to the user in the same form until they either give up, or are successful. With that said, I wouldn't try doing that until you have the redirection working. Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1626628 Share on other sites More sharing options...
Ezybusy Posted June 2 Author Share Posted June 2 (edited) @gizmola Thank you for you reply. I tried your suggestion, but i could not find out the issue. However, i just found a file (main.js) among the js file 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) { jQuery.ajax({ url: $(form).attr('action'), data: formData, type: "POST" }) .done(function (response) { // Make sure that the formMessages div has the 'success' class. formMessages.removeClass('error'); formMessages.addClass('success'); // Set the message text. formMessages.text(response); // Clear the form. $(form + ' input:not([type="submit"]),' + form + ' textarea').val(''); }) .fail(function (data) { // Make sure that the formMessages div has the 'error' class. formMessages.removeClass('success'); formMessages.addClass('error'); // Set the message text. if (data.responseText !== '') { formMessages.html(data.responseText); } else { formMessages.html('Oops! An error occured and your message could not be sent.'); } }); }; }; Edited June 2 by Ezybusy Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1626637 Share on other sites More sharing options...
Solution gizmola Posted June 4 Solution Share Posted June 4 No, just trying to use javascript to post the same data the form is posting, is not going to fix whatever is not working right now. Did you debug the form handling using the developer tools of your browser? You want to open developer tools and use the Network Tab. Then submit your form and you should be able to look at the request and the response. This will show you if the server is returning any errors. As I said previously, the code you posted is simple and I see no problems with it. It most likely does work, only you are not getting the emails, and that has nothing to do with the code, and everything to do with how email works and the way your server works. Email deliverability is complicated, and to debug an issue with it requires a full understanding of your ISP. In most cases, to send an email, you must use a mail server they supply. if (mail($recipient, $subject, $email_content, $email_headers)) { This is the line of code that actually sends the email, but what it really is doing is dumping the mail to your server's Mail Transfer Agent. I can't 100% tell you this is the case without knowing more about your ISP and your server, but by default that is how it works. So to the PHP code, it looks like the mail is sent, but from there the mail will simply disappear because the MTA tries to forward the mail and that gets rejected. This does not happen in realtime, so you will never know (without looking at logs) that the mail was never delivered. Many ISP's do not allow mail to be sent directly from a server, using the MTA, as a way of rejecting spam. So in that case, they require you to deliver mail to their internal servers, and it will then be sent by their mail server for you. You really need support from your hosting company to debug a complicated problem like email in many cases. 1 Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1626868 Share on other sites More sharing options...
Ezybusy Posted June 6 Author Share Posted June 6 On 6/4/2024 at 5:54 PM, gizmola said: No, just trying to use javascript to post the same data the form is posting, is not going to fix whatever is not working right now. Did you debug the form handling using the developer tools of your browser? You want to open developer tools and use the Network Tab. Then submit your form and you should be able to look at the request and the response. This will show you if the server is returning any errors. As I said previously, the code you posted is simple and I see no problems with it. It most likely does work, only you are not getting the emails, and that has nothing to do with the code, and everything to do with how email works and the way your server works. Email deliverability is complicated, and to debug an issue with it requires a full understanding of your ISP. In most cases, to send an email, you must use a mail server they supply. if (mail($recipient, $subject, $email_content, $email_headers)) { This is the line of code that actually sends the email, but what it really is doing is dumping the mail to your server's Mail Transfer Agent. I can't 100% tell you this is the case without knowing more about your ISP and your server, but by default that is how it works. So to the PHP code, it looks like the mail is sent, but from there the mail will simply disappear because the MTA tries to forward the mail and that gets rejected. This does not happen in realtime, so you will never know (without looking at logs) that the mail was never delivered. Many ISP's do not allow mail to be sent directly from a server, using the MTA, as a way of rejecting spam. So in that case, they require you to deliver mail to their internal servers, and it will then be sent by their mail server for you. You really need support from your hosting company to debug a complicated problem like email in many cases. Thank you very much for your time. I will look through your solution and try to figure it out. In case it does not work, I will get rid of the Ajax processing, then use pure php to process my form. Quote Link to comment https://forums.phpfreaks.com/topic/321254-how-to-use-php-to-redirect-to-another-page-after-form-submition/#findComment-1627022 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.