By now you've probably heard about AJAX and all its glory, but perhaps you have never ventured into that part of the web programming world. However, you have just built a simple contact form and thought about how great it would be to allow the user to submit this form without reloading the entire page. No problem, this is what we will do to make it happen using PHP:
- Build your contact form as usual, using the POST method. (Nothing different here.)
<form method="post" action="process_form.php" id="contactForm">
Your Name: <input type="text" name="name" /><br />
Your Email: <input type="text" name="email" /><br />
Comments: <textarea name="comments" rows="10" cols="40"></textarea><br />
<input type="submit" name="submit" value="submit" />
</form>
- Build your php form processing script as usual in PHP. (Nothing different here either.)
<?php
if ($_POST['submit']) {
$to = "email@domain.com";
$from = $_POST['email'];
$subject = "New Website Comments";
$message = "Comments were left on your website
from ".$_POST['email']." at ".date("g:i")." on ".date("M j, Y").".";
$message .= "\r\n".$_POST['name']."\r\n".$_POST['email'].
"\r\n".$_POST['comments'];
$headers = 'From: '.$_POST['email']."\r\n".'Reply-To: '.
$_POST['email']."\r\n".'X-Mailer: PHP/'.phpversion();
mail($to,$subject,$message,$headers);
}
?>
- (This is where we add code.) Download the jQuery library (get the minified version to save time) and the AJAX Form jQuery script. Once you have those two files, include them both like so:
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
Don't forget to change the paths and filenames to match the files you downloaded!
Then, all you need to do is add this script:
$(document).ready(function(){
$('#contactForm).ajaxForm(function() {
alert("Your message has been sent!");
});
});
That's it! When you submit the form, the data will be sent asynchronously and your page won't have to refresh. If it is processed successfully, you will see an alert telling you it has been sent. See above -- whatever you put in thatajaxFormfunction will happen. So if you really want to get fancy, you could use jQuery to hide the form only to reveal a new DIV that says thank you.
All the best at using AJAX!
No comments:
Post a Comment