This is a working example using the proposed example from jQuery and pajaja .
Decision:
Put this on the <head> web page.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
OR
Download jQuery and enable it in the same way.
The form:
Your contact form remains unchanged.
<form id="contactForm" action="assets/email.php" Method="POST"> <label for="name">Your Name</label> <input name="name" type="text" required placeholder="Please enter your name"> <label for="email">Email Address</label> <input name="email" type="email" required placeholder="Please enter your email address here"> <label for="message">Message</label> <textarea name="message" required></textarea> <button type="submit">Send</button> </form>
Returned data:
Add your answer element that you want in the body.
<div id="contactResponse"></div>
JavaScript:
Now place (preferably before </body> ) the javascript code:
<script> $("#contactForm").submit(function(event) { event.preventDefault(); var $form = $( this ), $submit = $form.find( 'button[type="submit"]' ), name_value = $form.find( 'input[name="name"]' ).val(), email_value = $form.find( 'input[name="email"]' ).val(), message_value = $form.find( 'textarea[name="message"]' ).val(), url = $form.attr('action'); var posting = $.post( url, { name: name_value, email: email_value, message: message_value }); posting.done(function( data ) { $( "#contactResponse" ).html(data); $submit.text('Sent, Thank you'); $submit.attr("disabled", true); }); }); </script>
Script action:
Your contact (PHP) file remains the same, but changes $ _GET to $ _POST:
<?php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $to = " xxx@xxx.xxx "; $subject = ""; $message = ""; $headers = "From: $email"; if( mail($to,$subject,$message,$headers) ) { echo "<h2>Thank you for your comment</h2>"; } else { echo "<h2>Sorry, there has been an error</h2>"; } ?>
Result:
Now you must submit the data from the form to submit, and then display the returned data in the #contactResponse element. The button will also set the text to "Sent, thanks" and also disable the button.