Main objective of a website is to get leads from the audience, contact forms are one of the efficient way to get customer information. Ajax based contact forms will give a nice user experience for the customer. When ajax is used user information can be submitted to the server in background without refreshing the page.
Download Script Live Demo
HTML Markup
Here is a basic html form with Name , Email and Subject field. Set the form id as “ajaxform”. Add a blank div with id “alert” where you want to show the server response. The browsers with HTML5 form validation support will prevent the fields with “required” attribute from submitting without data.
<div id="alert"></div><!--Response Holder--> <form action="contact.php" id="ajaxform" method="post" class="bossform"> <h1>Ajax Contact Form</h1> <label> <span> Name :</span> <input type="text" name="name" placeholder="Full Name" required/> </label> <label> <span> Email :</span> <input type="email" name="email" placeholder="Email Address" required/> </label> <label> <span>Message :</span> <textarea name="message" placeholder="Message" required></textarea> </label> <label> <span> </span> <input type="submit" id="submit" class="button" value="Send" /> </label> </form>
JavaScript
Here we make use for jQuery ajax api to submit form data to server without page refresh. Form data collected from the user is serialized before sending to the server using serializeArray() function it will serialize the form into a key-value pair string.
<script type="text/javascript"> $( document ).ready(function() { $("#ajaxform").submit(function(e){ var contactdata = $(this).serializeArray(); var submiturl = $(this).attr('action'); var submitbtn = $('#submit'); submitbtn.val('Sending...'); $("#ajaxform :input").prop("disabled", true); $.ajax({ url: submiturl, type: 'POST', dataType: "json", data : contactdata, success: function(response){ $('#alert').removeClass('alert alert-success'); $('#alert').removeClass('alert alert-danger'); if(response.status=="true"){ $('#alert').addClass('alert alert-success'); $("#ajaxform :input").prop("disabled", false); $('#ajaxform')[0].reset(); submitbtn.val('Send'); }else{ $("#alert").addClass('alert alert-danger'); $("#ajaxform :input").prop("disabled", false); submitbtn.val('Send'); } $('#alert').html(response.message).slideDown(); } }); e.preventDefault(); }); }); </script>
This javascript snippet will send the seralized form data via jQuery $.ajax method to the server.
preventDefault(); function is used to prevent the form submission. Multiple form submission can be avoided by disabling the form fields during the ajax action using the jQuery prop api – “#ajaxform :input”).prop(“disabled”, true);”
PHP mailer
This is a simple php mailer script which will return a json with state and message.
<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { //Replace with your email and subject line $to = "boss@codelikeaboss.com"; // To Email $mailsubject = 'New Contact From Codelikeaboss.com'; // Subject if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { $json_out = json_encode( array('status'=>'false', 'message' => 'Cheating huh ?')); die($json_out); } //Validation if( validate('name')|| validate('email') || validate('message')) { $json_out = json_encode(array('status'=>'false', 'message' => 'All fields are required')); die($json_out); } $name = $_POST["name"]; $email = $_POST["email"]; $message = $_POST["message"]; if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ $json_out = json_encode(array('status'=>'false', 'message' => 'Invalid email')); die($json_out); } /* Email Template */ $mailbody = "Hello! Name: $name E-mail: $email Message: $message "; $headers= "From: $name <$email>\r\n"; $headers.= "Reply-To: $name <$email>\r\n"; $headers.= "X-Mailer: PHP/" . phpversion()."\r\n"; $headers.= "MIME-Version: 1.0" . "\r\n"; $mail = @mail($to, $mailsubject, $mailbody , $headers); $mail = true; if(!$mail) { $output = json_encode(array('status'=>'false', 'message' => '<strong>Error!</strong> Failed to send mail')); die($output); }else{ $output = json_encode(array('status'=>'true', 'message' => '<strong>Success!</strong> We will get back to you soon.. :) ')); die($output); } } function validate($item){ if(isset($_POST[$item]) && $_POST[$item]!=""){ return false; }else{ return true; } } ?>Download Script Live Demo