How to make Ajax form with PHP & jQuery

by  
Share:
Ajax Form with PHP & jQuery

Contact form 7 is one of the most popular contact form plugin for wordpress. I am impressed with the error validation style. I always wanted to use it in one of my custom project, So I coded it and used it in a project. I am sharing it with all of you and the tutorial will explain how to make a custom ajax form like contact form 7 (wordpress plugin). This form is not just limited to contact form you can use it for database manipulations or to submit any form via Ajax (without page reloading).

Where can you use this form?

You can use this form as your contact form on your website. You can use this form to fetch data asynchronously, or even to perform database manipulation like insert/ update/ delete records.

View Demo

3 baby steps for creating form

  • Setup your form fields and message container with unique ids.
  • Validate the form with jquery
  • Submit the form via ajax

Setup your form fields and message container with unique id’s

Give id to the form field and setup a container for displaying error/success messages.

<form method="post" action="" name="contact_form" id="contact_form" >
<div class="row">
			<div class="label"><span style="color:#F00;">*</span>Name: </div>
			<div class="input-row" ><input name="your_name" id="your_name" type="text" class="textbox" autocomplete="off"><span id="your_nameErr" class="error" ></span></div>
		</div>

<div class="row">
			<div class="label"><span style="color:#F00;">*</span>Email: </div>
			<div class="input-row" ><input name="your_email" id="your_email" type="text" class="textbox" autocomplete="off"><span id="your_emailErr" class="error" ></span></div>

		</div>

<div class="row">
			<div class="label"></div>
			<div class="dummy-container" ><input type="submit" name="sub" value="Send" > <span class="loading"></span> </div>
		</div>

<!--Form final confirmation of form submission-->
<div class="output"></div>

</form>

As you can see above your_name has an ID as the field name and an equivalent container with err appended to it. Add a div with output class that will hold the notification for final form submission.

Stylize your form with css.

.loginbox{margin:0 auto;width:480px;padding:30px;border:1px solid #EB028F; height:auto;}
.row{ width:480px; height:auto; overflow:hidden; margin-bottom:10px; }
.label{ width:100px;color:#000; float:left;padding-top:5px;}
.input-row{ width:320px; height:32px; background-color:#FFF; float:left; position:relative; }
.input-textarea-row{ width:320px; height:65px; background-color:#FFF; float:left; position:relative; }
.dummy-container{ width:317px; height:32px; background:none; color:#000; float:left; padding:0px;position:relative;}

.textbox{ width:100%; height:24px;  border:1px solid #63F;outline:none; background:transparent; color:#000; padding:0px;  }
.textarea{ width:100%; height:57px;  border:1px solid #63F; outline:none; background:transparent; color:#000; padding:0px;  }
.error {
	background: none repeat scroll 0 0 #FFFFFF;
    border: 1px solid #F00;
    font-size: 11px;
    width: 314px;
	top:0%;
	left:0%;
    height:20px;
    padding:2px;
	position:absolute;
	display:none;
}

.loading{ background:url(ajax-loader.gif) no-repeat; width:32px; height:16px; position:absolute; margin-left:10px; margin-top:3px; visibility:hidden; }
.output{ margin:5px; widows:480px; padding:5px; display:none;}
.success{border:2px solid #0066FF;}
.failed{border:2px solid #FF0000;}

Validate the form with jQuery

I have used Jquery to validate the form. If there is an error on data validation, alert will be displayed above its relevant field.

<script type="text/javascript">
$(document).ready(function() {

$("#contact_form").submit(function() {
	$('.error').fadeOut(200);  
	$('.output').removeClass("success failed");  
	$('.output').css("display", "none");  
	// vlidate form here
	if(validateForm()) {
		sendForm();
	}     
	return false;
});

});
</script>

function validateForm() {
	 var errCnt = 0;

	 var your_name = $.trim( $("#your_name").val());

	// validate name
	if (your_name == "" ) {
		$("#your_nameErr").html("Enter your name.");
		$('#your_nameErr').fadeIn("fast"); 
		errCnt++;
	}  else if (your_name.length < 3 ) {
		$("#your_nameErr").html("Enter atleast 2 letter.");
		$('#your_nameErr').fadeIn("fast"); 
		errCnt++;
	}

	 if(errCnt > 0) return false; else return true;
}

Submit the form via ajax

Once the data is validated ( returns true) an ajax call is requested to the server side page, which returns error/success message in a json format. The result (json) is parsed and the message is notified to the user.

function sendForm() {

	$.ajax({
		type: "POST",
		url: "processform.php",
		data: $("#contact_form").serialize(),
		cache: false,
		beforeSend: function() {
        	$(".loading").css("visibility", "visible");
	    },
		success: function(html) {    
			$(".loading").css("visibility", "hidden");
			var obj = $.parseJSON(html);
			$(".output").html( obj.msg );
			$(".output").addClass( obj.msgtype );
			$(".output").slideDown("slow");
			$('#contact_form').trigger("reset");

		}

	});
}

PHP page to process the form and return confirmation message.
<?php
function clean($str) {
	return addslashes(trim($str));
}

$name = clean($_REQUEST["your_name"]);
$your_email = clean($_REQUEST["your_email"]);
$subject = clean($_REQUEST["your_subject"]);
$comments = clean($_REQUEST["your_comments"]);
$sex = clean($_REQUEST["your_sex"]);
$game = clean($_REQUEST["your_fav_game"]);

// now you can use the files to process form
// do whatever you need to do here
if (true) {
	echo json_encode( array("msg" => "Form Submitted Successfully", "msgtype" => "success"));
} else {
	echo json_encode( array("msg" => "Error Processing form. Please try later", "msgtype" => "failed"));
}
?>

View Demo
Share to download the Source Codes for FREE!
We're glad to give free downloads, but we need your love to carry on making that.
Please support us by sharing the page.

All your suggestion and feedback are welcome.

Get the latest updates directly in your inbox for FREE: Subscribe here

Share your feedback / let me know your doubts regarding this tutorial in the comment box given below.

Share:
Hasan

Shahrukh Khan (Hasan)

A software engineer who's a die-hard coder, blogger, dreamer and mentor with years of expertise in web development. Know more...

Related Posts

Khurshid Md Anwar on

Very good and knowledgeable tutorial. It enrich my knowledge many fold. Keep published in future too.

Reply
thesoftwareguy on

Thank You..

Reply
Shahriaz Khan on

Nice one. Keep posting stuff like this.

Reply
sanjay choudhury on

xcellent

Reply
Abi on

Hi, guy…

Just go through trough your site , it looks nice and productive , can we share some knowledge regarding the same site i want to build . i am tech guy working last 4 years as php web developer . appreciate your work

Reply
Shahrukh Khan on

Yeah sure.

Reply
Ravindra Mahto on

mind blowing sir… keep it up…
I really appriciate..

Reply
Shahrukh Khan on

Thanks

Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.