Simple AJAX / PHP Enquiry Form Tutorial
During my 7 or so years of working with PHP I have created literally 100′s of enquiry forms. From simple ones containing just a couple of fields to complex ones (sometimes maybe a bit too complex) containing hundreds of different variables. They all essentially however do the same thing; The user enters their details and clicks a submit button, the information is validated and emailed to a specified email address and the user is presented with a success message thanking them for their enquiry.
Don’t get me wrong, this method works absolutely fine, but what with the increasing popularity of AJAX over the past few years I decided to spruce things up a bit with my most recent form creations. By using AJAX to submit my forms I could seamlessly gather the user input and send the email without refreshing the whole page. The end result being a much smoother and user-friendly process.
Create a new file called ‘enquiry_form.html’ and place the below code into it:
The code above also generates a simple form containing two fields, ‘Name’ and ‘Enquiry’ and should look like the below image:
Now that we have our form we need a PHP script to actually send the email that contains the user’s details. To do so, create another new file called ‘process_enquiry.php’ and copy the below code into it:
<?php $to = "email@example.com"; $subject = "Enquiry Received"; $body = "A new enquiry has been received:\n\n"; $body .= "Name:\n".$_POST['name']."\n\n"; $body .= "Enquiry:\n".$_POST['enquiry']; mail($to, $subject, $body); echo 'success'; ?>
Simply change the email address on line 3 to your own address, upload the three files to a webserver (enquiry_form.html, process_enquiry.php and jquery.js) and you’ve just finished creating a very simple AJAX enquiry form. Go on, give it a go. With any luck once you click ‘Send Enquiry’, the form should disappear and present you with a message and an email should drop into your inbox containing the information you entered.
Please note, this tutorial has shown how to create an AJAX enquiry form in it’s most simplest format to show the core processes involved. In order to maintain simplicity and focus on the key elements there has been no validation or security efforts put into the code provided. Adding these once you have the code working is highly recommended.