W3C validation Service online

Simple Contact form using Jquery Ajax & PHP

Simple Contact form using Jquery Ajax & PHP

In this tutorial we will be creating a simple Ajax based Contact form using jQuery and PHP.

Why Ajax?

Because your visitors don’t have to reload the page in order to send you contact request throgh email, they can simply click Submit/Send button and the email gets sent instantly before their eyes, so it’s just fantastic, no more page reloads!

This Tutorial is pretty basic, you should be able to pull it off if you are bit familiar with HTML, PHP and jQuery.

First We need to create a basic HTML Contact form. We are going to use HTML5 attributes ‘required’. That will take care of form validation.

<form method="post" class="myform" action="process-form.php">
    <input type="text" name="name" placeholder="Your Name" required><br>
    <input type="email" name="email" placeholder="Your Email" required><br>
    <textarea rows="4" cols="20" name="message" placeholder="Your Message"></textarea><br>
    <input type="submit" name="send" value="Send"> <span class="output_message"></span>

Now, let’s add styling to this contact form we just created.

CSS Code

input[type=text], input[type=email], textarea {
    border:1px solid #ccc;
    margin:2px 0;
    font-family:Arial, Helvetica, sans-serif;
    box-shadow:inset 0 0 8px #e5e8e7;
input[type=submit] {
    padding:8px 25px;
    margin:2px 0;
    font-family:Arial, Helvetica, sans-serif;
input[type=submit]:hover {

jQuery Code

Now here is the Jquery code. Make sure you add jQeury file before this code.

$(document).ready(function() {
		// Add text 'loading...' right after clicking on the submit button. 
		var form = $(this);
			url: form.attr('action'),
			method: form.attr('method'),
			data: form.serialize(),
			success: function(result){
				if (result == 'success'){
					$('.output_message').text('Message Sent!');  
				} else {
					$('.output_message').text('Error Sending email!');
		// Prevents default submission of the form after clicking on the submit button. 
		return false;	

PHP Code

Now we need php file which will process our form and send email. Below is our PHP code for the process-form.php

if (isset($_REQUEST['name'],$_REQUEST['email'])) {
    $name = $_REQUEST['name'];
    $email = $_REQUEST['email'];
    $message = $_REQUEST['message'];
	// Set your email address where you want to receive emails. 
    $to = 'someaddress@example.com';
    $subject = 'Contact Request From Website';
    $headers = "From: ".$name." <".$email."> \r\n";
    $send_email = mail($to,$subject,$message,$headers);
	echo ($send_email) ? 'success' : 'error';

That’s it! we now have a neat looking simple contact form using Jquery Ajax & PHP. I hope you can now be able to create your own form by taking examples from here, or you can just download the entire code from link at right side and integrate it on your website right away.