I have updated the script to prevent multiple submissions by disabling all form fields upon a successful submission. I have also provided a demo in a zip file.
There are a ton of options and a ton of configurations for creating a contact form for your website. Some of them good, some of them great. Keep in mind, this is just an example, and should be treated as such. Better spam protection is a good idea, but for now we will stick with a simple to implement option.
Before we begin, you will need a few things already implemented on your site. Provided is their name and link to the CDN file. Place these in the footer of your page above the closing tag.
- jQuery Form Plugin//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.32/jquery.form.js
- jQuery Validate//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.min.js
The form is simple HTML with a few input fields, a “spam protection” field, and a hidden confirmation message triggered via the jQuery Validate plugin AJAX success call.
Here is some base CSS for the form, you will need to make adjustments to match your sites styling.
The PHP needed is just a basic form mail script. Change “firstname.lastname@example.org” to the email the form should send to, and “You have a message sent from your site” to whatever subject you would like the email to have. This script will reside on your server as process.php and not get inserted into your page.
Using jQuery Validate we can assure that the form is filled out properly before being sent in, and also prevent a bit of spam using a custom function.
First we state the rules for the form; what is required and what is not. Including a reference to a custom function we will make named answercheck, then we have a custom submit handler that uses the jQuery Form Plugin to submit the form via AJAX to the process.php script.
Once the form submits and returns, jQuery Form Plugin detect this and carries out the jQuery in the success* or **error callbacks. All these do is fade out the form and fade in the success or error divs.
This function can be placed in an existing js file such as the previous validate.js or in it’s own file which will then need to be referenced in your HTML.
Our quiz question to help prevent spam is “Name the small house pet that says meow“. You can ask anything you’d like, but I enjoy cats.
Our custom validation method requires a specific answer of cat as stated at /^\bcat\b$/, and will return a custom error notification as long as the answer is incorrect.
There you go, a simple PHP, jQuery, and AJAX powered contact form.
You can see it in action on my portfolio at http://portfolio.ajtroxell.com. Feel free to submit it to see the AJAX/jQuery process after submission. Sorry, the demo is no longer available.