Reputation: 1432
So basically I am trying to create a form that users can input their name, e-mail, message, etc., click submit, and the information gets compiled and sent to my e-mail address. What happens when you click submit is you get redirected to a new page, joeyorlando.me/php/index.php.
What I would like to have happen upon clicking submit is to have a small box pop up near the submit button saying, "Thanks for your submission" (or something of the sort), and the page not get redirected, instead you would remain on the same page as the form.
How can I prevent the submit button from sending you to this new page? Any advice would be much 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 = '[email protected]';
$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>';
}
}
?>
Upvotes: 3
Views: 2639
Reputation: 13
As suggested by Jake, you could use Ajax or alternatively, you could write the form in the same php file. Then, when after all verification steps, if all is well, 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>
Upvotes: 0
Reputation: 61
AJAX will be good in this case. AJAX will submit your form without refreshing it and you can show appropriate message on successful submission.
Upvotes: 0
Reputation: 11430
You can use AJAX to send post the form to another script and wait for a response either showing the error or 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>
Upvotes: 2