Reputation: 259
When I submit the form it redirects me back to the same page using this code
PHP
if( empty($errors))
{
$to = $myemail;
$email_subject = "Contact form submission: $name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Message \n $message";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: index.html');
}
What I want it to do is stay on the same page without refreshing and then hide the div..
HTML
<div class="footer">
<div id="containerfooter">
<form method="POST" name="contactform" action="contact-form-handler.php" class="NewsLetter" class="NL__field NL__email">
<p>
<label for='name'>Your Name:</label> <br>
<input type="text" name="name" class="NL__field NL__email">
</p>
<p>
<label for='email'>Email Address:</label> <br>
<input type="text" name="email"> <br>
</p>
<p>
<label for='message'>Message:</label> <br>
<input type="text" name="message">
</p>
<input type="submit" value="Submit"><br>
</form>
</div>
</div>
JQuery
$('form').submit(function(){
$('#containerfooter').hide();
});
Upvotes: 0
Views: 519
Reputation: 40038
Forms vs AJAX
Forms allow you to take user-entered data and send it to another PHP file for processing. However, when the form is submitted, navigation moves to the other PHP page (the one specified in the action=""
attribute on the form tag:
<form method="POST" name="contactform" action="contact-form-handler.php" class="NewsLetter" class="NL__field NL__email">
In above tag, upon clicking submit button, the browser navigates to contact-form-handler.php
AJAX was invented to solve that, allowing you to send the data to the second PHP file, and (optionally) receive different data/html back without changing or refreshing the current page
Here is an SO post with some very simple examples of AJAX. It is not difficult - just copy the examples to your server and make them work on your server. Play with them a bit. The fifteen minutes you spend doing that will save you hours.
AJAX request callback using jQuery
Note: In this day and age, it is almost never necessary to use FORMs. Everything can be done via AJAX - and it's so simple, why wouldn't you?
Note2: When using AJAX with <form></form>
tags, you must use e.preventDefault()
to keep the form tag from navigating you away from the current page (the form tag's default action):
$('myButton').submit(function(evt){
evt.preventDefault();
//the rest of your js code, including ajax code block
Upvotes: 1