PHP Form not showing Success or Error messages when submitted

I checked so many posts on here but I am unable to fix this.
I have a PHP form and although the email is sent it doesn’t show any massage and I don’t know what I am missing.

In the PHP it mentions a success and failed but no reference on where that message sits? I set up PHP forms before but this is throwing me off.

Anyone can help, please?

The sendmail.php code

<?php

// Define some constants
define( "RECIPIENT_NAME", "Email" );
define( "RECIPIENT_EMAIL", "email@email.com" );


// Read the form values
$success = false;
$senderName = isset( $_POST['username'] ) ? preg_replace( "/[^\s\S\.\-\_\@a-zA-Z0-9]/", "", $_POST['username']) : "";
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

// If all values exist, send the email
if ( $senderName && $senderEmail && $message) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
  $headers = "From: " . $senderName . "";
  $msgBody = " Email: ". $senderEmail . " Message: " . $message . "";
  $success = mail( $recipient, $headers, $msgBody );

  //Set Location After Successsfull Submission
  header('Location: contact.html?message=Successfull');
}

else{
	//Set Location After Unsuccesssfull Submission
  	header('Location: contact.html?message=Failed');	
}

?>

The HTML code of the contact.html:

 <!--Contact Section-->
    <section class="contact-section">
        <div class="auto-container">

            <div class="info-container">
                <div class="row clearfix">
                </div>
            </div>

            <div class="contact-container">
                <div class="row clearfix">
                    <!--Form-->
                    <div class="form-column col-lg-6 col-md-12 col-sm-12">
                        <div class="inner wow fadeInLeft" data-wow-delay="0ms" data-wow-duration="1500ms">
                            <div class="sec-title">
                                <h2>Send <strong>Your Message</strong></h2>
                                <div class="lower-text">Don’t Hesitate to Contact Us</div>
                            </div>
                            <div class="default-form contact-form">
                                <form method="post" id="contact-form" action="sendemail.php">
                                    <div class="row clearfix">          
                                        <div class="form-group col-lg-6 col-md-6 col-sm-12">
                                            <div class="field-label">Name</div>
                                            <div class="field-inner">
                                                <input type="text" name="username" placeholder="Your Name" required="" value="">
                                            </div>
                                        </div>

                                        <div class="form-group col-lg-6 col-md-6 col-sm-12">
                                            <div class="field-label">Email</div>
                                            <div class="field-inner">
                                                <input type="email" name="email" placeholder="Email Address" required="" value="">
                                            </div>
                                        </div>

                                        <div class="form-group col-lg-12 col-md-12 col-sm-12">
                                            <div class="field-label">Message</div>
                                            <div class="field-inner">
                                                <textarea name="message" placeholder="Write your message..." required=""></textarea>
                                            </div>
                                        </div>
                
                                        <div class="form-group col-lg-12 col-md-12 col-sm-12">
                                            <button type="submit" class="theme-btn btn-style-three"><span class="btn-title">Send Your Message</span></button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </section>

Thank you anyone who can help. :slight_smile:

Ok so you are passing the message back to contact.html and that is where you are saying it is not showing the message, on the page right?

Assuming this is what you are talking about, it is because you don’t have anything on contact.html that reads that passed message, evaluates it and displays it on page.

Now I would suggest that unless you configured the server to pass .html files to PHP, you probably want to make sure this is contact.php and not contact.html. Then in the body of the page you are going to want to put in some conditional logic to look for a message being passed to the page. Based on that message you can then display any error/success message.

<div class="message-response">
<?php
    if (isset($_GET['message'])) { //<--- Read the message passed to page
           if ( $_GET['message'] === 'Successfull') { //<-- Was it successful? If so, display success
                echo "Hurray, message sent successfully!";
           } else {
                echo "Uh oh, something went wrong."; // <-- Error? Say so.
          }
    }
?>
</div>
<div class="inner wow fadeInLeft" data-wow-delay="0ms" data-wow-duration="1500ms">
                            <div class="sec-title">
                                <h2>Send <strong>Your Message</strong></h2>
                                <div class="lower-text">Don’t Hesitate to Contact Us</div>
                            </div>

Hopefully this is what you are talking about. Otherwise please clarify a bit further on what is exactly not happening that you think it shou.d :slight_smile:

1 Like

?message=Successfull and ?message=Failed are query strings.

Reference:
https://www.w3schools.com/jsref/prop_loc_search.asp

You can run JavaScript on page load to display the appropriate message.

However, I think it is better to have separate pages for success and fail rather than go back to the page with the form.

In the ‘header’ functions you need the full URLs starting with http…

1 Like

Thank you for your answer. The issue is related that a client had his website done from a template and now asking me to edit some bits.
So, I have created a contact.php, pasted the code you wrote above and changed the code in sendmail.php to the following but it’s still not working:

<?php

// Define some constants
define( "RECIPIENT_NAME", "Michele" );
define( "RECIPIENT_EMAIL", "info@example.com" );


// Read the form values
$success = false;
$senderName = isset( $_POST['username'] ) ? preg_replace( "/[^\s\S\.\-\_\@a-zA-Z0-9]/", "", $_POST['username']) : "";
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

// If all values exist, send the email
if ( $senderName && $senderEmail && $message) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
  $headers = "From: " . $senderName . "";
  $msgBody = " Email: ". $senderEmail . " Message: " . $message . "";
  $success = mail( $recipient, $headers, $msgBody );

  //Set Location After Successsfull Submission
  header('Location: contact.php?message=Successfull');
}

else{
	//Set Location After Unsuccesssfull Submission
  	header('Location: contact.php?message=Failed');	
}

 if (mail($senderName, $senderEmail, $message)){
		$success = "Message successfully sent";
	}else{
		$success = "Message Sending Failed, try again";

?>

Your code shows:

But you say the page is sendmail.php ? If that is so that would be the problem.

If not, when you say it is “not working” what do you mean - what happens?

Also, the example given to you for contact.php uses _GET but you used _POST. You don’t use the

syntax with POST.

I am no expert in this but wonder if this is the issue?

(also, you have spelt successful incorrectly but as it is only being used as a string and the same incorrect spelling is being tested for then that shouldn’t be a problem!)

Actually I would strongly suggest not to do this. It is often much easier and better to go back to the same page as the form and just display the error messages than breaking it out into other pages. Anyone who has done much bigger projects will tell you, having separate pages just to show messages like this is really tedious and time consuming.

@johnbiondini The code you added there with setting the $success variable doesn’t really address the issue of displaying based on that variable. Look back at my example. The code I am showing is back in your HTML form code. That is the page that gets passed the “message” value as part of the URL. Are you able to alter that template at all for the client or is that something that is fixed in place?

@Martyr2
If the form submission is successful there is usually no point in continuing to display the form. Is it not true that most websites redirect to a separate success page? I have a client website with about 10 forms and just one success page. That’s not tedious or time-consuming.

In this case the form already has HTML5 validation so the chance of failure is small. A failure web page could have a ‘Back’ button to navigate back to the form. I accept that it is sometimes necessary to have more sophisticated client-side JavaScript validation and/or server-side PHP validation. Such validation should highlight the input fields that are failing validation and provide appropriate messages. Your code is not doing that.

If the form is successful, sure you can go to another page. When submitting the form however, you typically submit it to itself in the case of the opposite outcome, it is not successful in which case you would show the error message. Now having said that, it also depends. In many cases the form may show a successful and still redirect back to the form. Think of a form that “saves”. Sometimes you redirect back with a success message only to show the form again for future edits.

Now if you were referring simply that they could just redirect if the outcome was successful, then I agree. I was just saying that in most cases you submit to itself and if it is successful, then do something. Otherwise you want to go back to the form again with an error message so the user can try again. If I misunderstood your statement, then I apologize. But I do stand by the idea that you typically would submit back to itself because a success doesn’t always mean a separate page. I was also under the impression you were also saying a separate page for failure as well.

But in any case, the typical pattern is you submit the form back to its page, if successful do something and if not, show the message and display the form again.

External data can be anything, can come from anywhere, and cannot be trusted. You MUST validate data on the server before using it, and then you must use it in a safe way appropriate for the context.

Client-side validation is just a nicety for legitimate visitors.

1 Like

My mistake, the page is called sendmail.php.

If you fill up the details and click “Send” the email will be delivered but the user just sees the page refreshed and no indication on whether the email was successfully sent or not.

I literally tried everything. :tired_face:

The returned page on sending is contact.html?message=Successfull

How is your contact.html page supposed to process the parameter passed? You need JS or PHP for this.

I can see several issues, most of which have been mentioned above.

  1. Your form uses the method PUT but you are using the syntax for GET (using “?”)
  2. Your form action is “sendemail.php” but your page is called “sendmail.php” (although if that were the case then I would not expect the email to send at all)
  3. Your contact page suffix is .html - it should be .php or otherwise the PHP will not run.

I think I solved it! Thank you people, that was super helpful! :slight_smile:

How did you fix it?

I had to make the contact.html into a php file and then add the success/fail messages. :slight_smile: