Display "Form sent successfully!" on same page of the form after form submission

I’m working on a contact form.
It’s working fine. User fills up contact form, processed by PHP, if successful, the user will be redirected to a thank you page then will redirect back to the main webpage after 3 or so seconds.

I want the form to “not” redirect to a different page after form submission, but instead just display a text below the form saying for example “Form sent successfully!” and the textboxes shall be cleared.

And if it’s possible to not include any PHP code in the main webpage as I want it to remain a .html file.

I’m a beginner in PHP, so coding on my own is not possible for now but I know a few terms and can follow basic codes (I think).

Here are the codes.

index.html

<!DOCTYPE html>
<html>
	<head>
	</head>
	<body>
		<!-- CONTACT FORM : BEGIN -->
	    <div>
	        <form method="post" name="myemailform" action="form-to-email.php">
	           	<div>
	                <input type="text" placeholder="Your Name" name="name" id="name" required>
	            </div>
	            <div>
	                <input type="email" placeholder="Your Email" name="email" id="email" required>
	            </div>
	            <div>
	                <input type="text" placeholder="Your Phone" name="phone" id="phone">
	            </div>
	            <div>
	                <textarea id="msg" placeholder="Describe your mining need" name="message" id="needs" required></textarea>
	            </div>
	            <div>
	                <input class="form-submit-button-text" type="submit" name='submit' value="SUBMIT" style="width: 200px;">
	            </div>
	        </form>
	    </div>
	    <!-- CONTACT FORM : END -->
    </body>
</html>

thank-you-page.html

<!DOCTYPE html> 
<html>
<head>
	<title>Thank you!</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="TSW WebCoder">
</head>
<body>
    <div class="part-five part-four" id="Get-Started" style="display: flex; align-items: center; justify-content: center; background-size: auto !important;">
        <p>Thank you for reaching out to us. We will get back to you shortly. Please click <a href="index.html" style="text-decoration: none; color #0986d9 !important;;">here </a> if you are not redirected within a few seconds.</p>
    </div>
    <script src="http://code.jquery.com/jquery-3.3.1.js"></script>
    <script>
        setTimeout(function () {
            window.location.replace("index.html"); //will redirect to main page (index.html)
        }, 3000); //will call the function after 3 secs.
    </script>   
</body>
</html>

form-to-email.php

<?php
if(!isset($_POST['submit'])) {
	//This page should not be accessed directly. Need to submit the form.
	echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email)) {
    echo "Name and email are mandatory!";
    exit;
}

if(IsInjected($visitor_email)) {
    echo "Bad email value!";
    exit;
}

$email_from = 'email@example.com';//<== update the email address
$email_subject = "Inquiry";
$email_body = "You have received a new message from the user $name.\n".
    "Here is the message:\nName : $name \nE-mail : $visitor_email \nPhone : $phone \nMessage : $message \n".
    
$to = "email@example.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');

// Function to validate against any email injection attempts
function IsInjected($str) {
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str)) {
    return true;
  }
  else {
    return false;
  }
}
?> 

If anyone can give me an idea on how to do what I wanna do, that would be great.
I’ve uploaded these to a web host so I can link you up to it Just let me know and I’ll send it to you via pm. Thank you!

I think the only way (but certainly it seems to be the most popular way) is to use Ajax to submit the code. Instead of using the normal form submission via HTML, you would have some JavaScript code that traps the submit button press. That code would grab the data from the form, call the PHP code, await the response from the PHP, and then act accordingly.

Loads of examples on here, you might also want to look in the JavaScript section of the board as there are a few topics on this subject there in recent days. I note you already have jQuery in your code, that can make the form submission quite easy.

1 Like

Hi, @droopsnoot.

I think I’ve already accomplished what I was trying to do. Though, I’m not really sure if what I did was “fine” if we’re going to consider factors like security, etc.

Mind if I send you a link to the site and take a look? I can’t post the link due to confidentiality reasons.

Thank you!

I don’t mind you sending a link and I’ll try to have a look, but I’m no expert in security matters - there are plenty of recent threads on here that give some ideas on that. And, of course, I won’t be able to see the code, so you might be doing something really terrible in the PHP. On confidentiality, it’s a bit strange that you won’t post the link, but you don’t mind sending it to a total stranger. Better to anonymise the code and post it, and then people who know about security and stuff can weigh in as well.

1 Like

I’m just going to post the codes here.

     <script>
            $("#contact-form").on('submit',function(event) {
                event.preventDefault(); // to prevent default page reloading
                var dataString = $(this).serialize(); // to get the form data
                
                $.ajax({
                    type: "POST",
                    url: "form-to-email.php",
                    data: dataString,
                    success: function(data){
                        $('#contact-form')[0].reset(); // to reset form data
                    }
                }).done(function(data){
                    setTimeout(function () {
                        alert("Form submitted successfully! We'll get back to you soon. Thank you.");
                    }, 2000);
                    //alert("Form submitted successfully! We'll get back to you soon. Thank you."); // This will be called after the ajax executed
                });

            });
        </script>

What I originally wanted was to display a block of text below the code after form submission (I just can’t do it), but I think this will do for now.

index.html

<!DOCTYPE html>
<html>
	<head>
	</head>
	<body>
		<!-- CONTACT FORM : BEGIN -->
	    <div>
	        <form method="post" name="myemailform" action="form-to-email.php">
	           	<div>
	                <input type="text" placeholder="Your Name" name="name" id="name" required>
	            </div>
	            <div>
	                <input type="email" placeholder="Your Email" name="email" id="email" required>
	            </div>
	            <div>
	                <input type="text" placeholder="Your Phone" name="phone" id="phone">
	            </div>
	            <div>
	                <textarea id="msg" placeholder="Describe your mining need" name="message" id="needs" required></textarea>
	            </div>
	            <div>
	                <input class="form-submit-button-text" id="button" type="submit" name='submit' value="SUBMIT" style="width: 200px;">
	            </div>
	        </form>
	    </div>
	    <!-- CONTACT FORM : END -->
    </body>
</html>

Updated form-to-email.php

<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email)) 
{
    echo "Name and email are mandatory!";
    exit;
}

if(IsInjected($visitor_email))
{
    echo "Bad email value!";
    exit;
}

$email_from = 'mail@example.com';//<== update the email address
$email_subject = "Inquiry";
$email_body = "You have received a new message from the user $name.\n".
    "Here is the message:\nName : $name \nE-mail : $visitor_email \nPhone : $phone \nMessage : $message \n".
    
$to = "mail@example.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?> 

That’s fair. Just don’t want to post it where anyone can see it and I know you won’t post it elsewhere or share it with anyone because you won’t gain anything from it. :slight_smile:

I didn’t know that others can’t see the code though. :pensive:
Anyway, the full php code is above.

Thank you!

I’d normally just have a <div> and set the content to whatever you want to indicate success, or even just manipulate the visibility of it in your success() function.

The PHP code only runs on the server, and all outsiders see is the result of it, whatever it echoes out. Can see the HTML and JS of course.

The first comment on the PHP is that you should not use mail() as it’s often described as unreliable. Have a look at PHPMailer or Swiftmailer.

1 Like

I don’t know why I did not think of this.
Fixed it now.

Added this to the .html

<div class="contactform-messages">Thank you for reaching out to us. We'll get back to you shortly!</div>

style

.contactform-messages {
    display: none;
}
.active {
    display: block;
}

script

     <script>
            $("#contact-form").on('submit',function(event) {
                event.preventDefault(); // to prevent default page reloading
                var dataString = $(this).serialize(); // to get the form data
                $.ajax({
                    type: "POST",
                    url: "form-to-email.php",
                    data: dataString,
                    success: function(data){
                        $('#contact-form')[0].reset(); // to reset form data
                    }
                }).done(function(data){
                    setTimeout(function () {
                        $('.contactform-messages').addClass('active');
                    }, 500);
                });
            });
        </script>

I’ll look into these. I actually just found the PHP code online. I think I’ve come across PHPMailer already but it was too complicated for me to understand.

Thank you so much, @droopsnoot.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.