Simple AJAX Contact Form

We have been very busy with various projects recently, so have not had much time to post any guides recently. We have had a few people ask recently how they would make an AJAX contact form, so we thought we would write a post and tell everyone how it’s done. This contact form also includes a maths question (because we hate CAPTCHA’s) to help prevent spam submissions.

Remember that this is a guide, you are free to edit and change the files for your requirements.

» Click Here to see the AJAX contact form in action

» Click Here to download the files

Firstly create the page which you want the form to be on, ensure that jQuery and the send jQuery script are included within the head.

&lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js&quot;&gt;&lt;/script&gt;<br />
&lt;script type=&quot;text/javascript&quot; src=&quot;formSubmit.js&quot;&gt;&lt;/script&gt;

Next, you need to include the html form on your page. This includes the actual fields the user will put their info in, the success message which by default should be hidden and the loading and submit button. Within the body tags of the page put in the following html…

<div class="contactWrap"> 
<div class="success">Thank You! We will get back to you shortly</div> 
<form action="send.php" method="post" id="side-enquiry"> 
<span class="enquiry-title">Get in Touch!</span> 
<p>Fill in your details below, and we will get back to you.</p> 
<div class="msg"></div> 
<table> 
<tr> 
<td style="width:90px;"><label>Full Name</label></td> 
<td><input name="name" id="name" type="text" value="" /></td> 
</tr> <tr> <td><label>Email</label></td> 
<td><input name="email" id="email" type="text" value="" /></td> 
</tr> <tr> <td><label>Telephone</label></td> 
<td><input name="number" id="number" type="text" value="" /></td> 
</tr> <tr> <td><label class="detLab">Details</label></td> 
<td><textarea rows="6" cols="10" name="comment" id="comment"></textarea></td> 
</tr> <tr> <td> <label>What is 2 + 2?</label> <span class="info" style="margin:-10px 0 0 0"></span> 
<div class="infoPop"> <p><strong>Fight Spam!</strong></p> <p>To help prevent spam, we have included this simple maths question.</p> 
</div> </td> <td><input name="security" id="security" type="text" /></td> 
</tr> </table> <button type="submit" class="enquiry-submit">Submit</button> 
<div class="loading"></div> 
</form> 
</div> 

Now you have the html it is time to check the jQuery script, and the php script that sends the actual email to you. Below is an example of the jQuery script which has comments in to guide you through what does what.

// This creates the function to validate the email address function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^(("[w-+s]+")|([w-+]+(?:.[w-+]+)*)|("[w-+s]+")([w-+]+(?:.[w-+]+)*))(@((?:[w-+]+.)*w[w-+]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$)|(@[?((25[0-5].|2[0-4][d].|1[d]{2}.|[d]{1,2}.))((25[0-5]|2[0-4][d]|1[d]{2}|[d]{1,2}).){2}(25[0-5]|2[0-4][d]|1[d]{2}|[d]{1,2})]?$)/i); return pattern.test(emailAddress); }; // This makes this jQuery script use a different selector i.e. formQuery instead of $ var formQuery = jQuery.noConflict(); formQuery(document).ready(function() { // This shows/hides the maths question popup formQuery(".info").mouseover(function() { formQuery(this).next(".infoPop").show(); }); formQuery(".info").mouseout(function() { formQuery(this).next(".infoPop").hide(); }); // This creates the function when the form is submitted formQuery('.enquiry-submit').click(function () { // This sets variables for all of the form inputs var name = formQuery('input[name=name]'); var email = formQuery('input[name=email]'); var number = formQuery('input[name=number]'); var comment = formQuery('textarea[name=comment]'); var security = formQuery('input[name=security]'); // If name field is empty, highlight it and display validation error if (name.val()=='') { name.addClass('hightlight'); formQuery('.msg').show(); formQuery('.msg').html("<div class='message'></div>"); formQuery('.message').html("Please fill in all fields."); return false; } else name.removeClass('hightlight'); // If email field is empty or invalid, highlight it and display validation error if (email.val()=='') { email.addClass('hightlight'); formQuery('.msg').show(); formQuery('.msg').html("<div class='message'></div>"); formQuery('.message').html("Please fill in all fields."); return false; } else if(!isValidEmailAddress(email.val())){ email.addClass('hightlight'); formQuery('.msg').show(); formQuery('.msg').html("<div class='message'></div>"); formQuery('.message').html("Please enter a valid email."); return false; } else email.removeClass('hightlight'); // If details textarea is empty, highlight it and display validation error if (comment.val()=='') { comment.addClass('hightlight'); formQuery('.msg').show(); formQuery('.msg').html("<div class='message'></div>"); formQuery('.message').html("Please fill in all fields."); return false; } else comment.removeClass('hightlight'); // If maths question field is empty or incorrect, highlight it and display validation error if (security.val()=='') { security.addClass('hightlight'); formQuery('.msg').show(); formQuery('.msg').html("<div class='message'></div>"); formQuery('.message').html("Please fill in all fields."); return false; } else if (security.val()!='4') { security.addClass('hightlight'); formQuery('.msg').show(); formQuery('.msg').html("<div class='message'></div>"); formQuery('.message').html("Security question incorrect."); return false; } else security.removeClass('hightlight'); // Compile field variables into data var data = 'name=' + name.val() + '&email=' + email.val() + '&number=' + number.val() + '&comment=' + encodeURIComponent(comment.val()) + '&security=' + security.val(); // Show the loading icon and remove any error messages formQuery('.loading').show(); formQuery('.msg').hide(); // Start AJAX send formQuery.ajax({ // Enter below the full path to your "send" php file url: "https://www.thewebtaylor.com/guides/demo/ajax-form/send.php", type: "POST", data: data, cache: false, success: function (html) { // If form submission is successful if ( html == 1 ) { formQuery('.loading').hide(); formQuery('#side-enquiry').hide(); formQuery('.success').show(); } // Double check if maths question is correct else if ( html == 2 ) { formQuery('.loading').hide(); formQuery('.msg').show(); formQuery('.msg').html("<div class='message2'></div>"); formQuery('.message2').html("Security code is incorrect."); } // If ther was an error with sending the message else { formQuery('.loading').hide(); formQuery('.loading').hide(); formQuery('.msg').show(); formQuery('.msg').html("<div class='message2'></div>"); formQuery('.message2').html("Error, please try again."); } } }); return false; }); }); 

You will see in the script above that there is a link to a file called send.php, it is important that this is the full URL to the file as the message will not send. Below is what the send.php script should look like…

$EmailFrom = Trim(stripslashes($_POST['email'])); // Your email address below $EmailTo = "email@email.com"; $Subject = "Enquiry"; $Name = Trim(stripslashes($_POST['name'])); $Email = Trim(stripslashes($_POST['email'])); $Number = Trim(stripslashes($_POST['number'])); $Comment = Trim(stripslashes($_POST['comment'])); $Website = Trim(stripslashes($_POST['website'])); $Security = Trim(stripslashes($_POST['security']));</code> // prepare email body text $Body = ""; $Body .= "Name: "; $Body .= $Name; $Body .= "n"; $Body .= "n"; $Body .= "Email: "; $Body .= $Email; $Body .= "n"; $Body .= "n"; $Body .= "Number: "; $Body .= $Number; $Body .= "n"; $Body .= "n"; $Body .= "Comment: "; $Body .= $Comment; // send email if ($Security == "" || $Security != "4" ) { echo "2"; } else { $success = mail($EmailTo, $Subject, $Body, "From: "); if ($success) { echo "1"; } else{echo "error";} } 

If you look at the demo and have a play around with the files, you will see how much of a clever, flexable and compact AJAX contact form this really is.

» Click Here to see the AJAX contact form in action

» Click Here to download the files

We would love to hear your comments and feedback, so if there is anything we have missed out, or you just want to say how this script helped you… just give us a shout in the comments below 🙂

Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Google Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358