It is necessary to prevent opening a new page when submitting the PHP $ _POST form.
So basically I'm trying to create a form where users can enter their name, email, message, etc., submit a message, and the information will be compiled and sent to my email address. What happens is when you click the submit button, you are redirected to a new page, joeyorlando.me/php/index.php.
What I would like to get when the submit button is clicked is for a small window to appear next to the submit button that says "Thanks for your submission" (or something like that) and the page is not is redirected, instead you will remain on the same page as the form.
How can I prevent the submit button from being sent to this new page? Any advice would be greatly appreciated!
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = $_POST['human'];
$from = 'From: $firstname $lastname';
$to = 'joey@joeyorlando.me';
$subject = 'You Have a New Form Submission!';
$body = "From: $firstname $lastname\n Company: $company Phone: $phone \n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if ($firstname != '' && $lastname != '' && $email != '' && $message != '') {
if ($human == '14') {
if (mail ($to, $subject, $body, $email)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '14') {
echo '<p>You answered the question incorrectly!</p>';
}
} else {
echo '<p>You need to fill in all required fields!!</p>';
}
}
?>
source to share
You can use AJAX to submit a form post to another script and wait for a response with either an error message or a success message.
<script>
$(document).ready(function() {
$('#my-form').submit(function() {
$.ajax({
url: 'script.php',
method: 'post,'
/* TODO: add data */
}).done(function(response) {
alert(response);
});
return false;
});
});
</script>
<form id="my-form" method="post" action="script.php">
<input type="submit" value="submit">
<form>
source to share
As suggested by Jake you can use Ajax or alternatively you can write the form in the same php file. Then, when after all the verification steps, if everything is fine, echo Success;)
if(isset($_POST['submit']))
{
//the code you've posted + sucess message
}
<form name="name_of_form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
//Input form
</form>
source to share