Submit Form Without Page Refresh

Hello friends, welcome to my another small web application submit form without page refresh. In my previous blog I show you how to create Ajax File Upload with Progress Bar. Today I will create another small application with the help of ajax and jQuery. We use html form for every website to submit user data. After submit the form, page will refresh. It takes some time to submit the form. But we can bypass the page refresh using Ajax.

Ajax is a technology by which you can submit your data with out page refresh. Now for submit form without page refresh application, I create a simple contact form with name, email and message. You have to put your contact data into the form. After clicking “Send Mail” button the form data will go to a php page using ajax request from where the mail will transfer.




You need only three steps to create this application. First of all you need to make a HTML form.

Step1: Create HTML form markup

This is a very basic html form where I include a css file(style.css), jQuery main library(jquery-1.11.1.min.js) and send_data.js file where I wrote the form validation code and send data to a php file.

<!DOCTYPE html>
<html lang="en"><!-- This is a demonstration of HTML5 goodness with healthy does of CSS3 mixed in --><head>
    
    <title>Ajax contact form using captch in PHP</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <!--[if IE]>
    	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link rel="stylesheet" href="style.css" type="text/css" media="screen">
	<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
	<script type="text/javascript" src="js/send_data.js"></script>
</head>
<body>
   <div  class="cover">	
		<div id="result"></div>
		<div id="contactform"> 
			<p class="contact"><label for="name">Name</label></p> 
			<input id="name" name="name" placeholder="Yourname" type="text"> 
			 
			<p class="contact"><label for="email">Email</label></p> 
			<input id="email" name="email" placeholder="admin@admin.com" type="text">
			 
			<p class="contact"><label for="comment">Your Message</label></p> 
			<textarea name="comment" id="comment" tabindex="4"></textarea> <br>
			<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
		</div> 
    </div>       
</body>
</html>

Step2: Create send_data.js form input field validation and send ajax request to the php file

All the jQuery code is well commented. So do not worry.

$(document).ready(function(){
	$("#submit").click(function() { 
		//get input field values
		var name       		= $('#name').val(); 
		var email      		= $('#email').val();
		var message   	    = $('#comment').val();
		var flag = true;
		/********validate all our form fields***********/
		/* Name field validation  */
        if(name==""){ 
            $('#name').css('border-color','red'); 
            flag = false;
        }
		/* email field validation  */
        if(email==""){ 
            $('#email').css('border-color','red'); 
            flag = false;
        } 
		/* message field validation */
        if(message=="") {  
           $('#comment').css('border-color','red'); 
            flag = false;
        }
		/********Validation end here ****/
		/* If all are ok then we send ajax request to email_send.php *******/
		if(flag) 
        {
			$.ajax({
				type: 'post',
				url: "email_send.php", 
				dataType: 'json',
				data: 'username='+name+'&useremail='+email+'&message='+message,
				beforeSend: function() {
					$('#submit').attr('disabled', true);
					$('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
				},
				complete: function() {
					$('#submit').attr('disabled', false);
					$('.wait').remove();
				},	
				success: function(data)
				{
					if(data.type == 'error')
					{
						output = '<div class="error">'+data.text+'</div>';
					}else{
						output = '<div class="success">'+data.text+'</div>';
						$('input[type=text]').val(''); 
						$('#contactform textarea').val(''); 
					}
					
					$("#result").hide().html(output).slideDown();			
					}
			});
		}
	});

	//reset previously set border colors and hide all message on .keyup()
	$("#contactform input, #contactform textarea").keyup(function() { 
		$("#contactform input, #contactform textarea").css('border-color',''); 
		$("#result").slideUp();
	});
});

Create email_send.php where I put server side validation and php mail send code

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{

	//check if its an ajax request, exit if not
	if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
	
		//exit script outputting json data
		$output = json_encode(
		array(
			'type'=>'error', 
			'text' => 'Request must come from Ajax'
		));
		
		die($output);
	} 
	
	//check $_POST vars are set, exit if any missing
	if(!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"]))
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
		die($output);
	}

	//Sanitize input data using PHP filter_var().
	$username       = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
	$useremail      = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
	$message        = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);
	
	//additional php validation
	if(strlen($username)<4) // If length is less than 4 it will throw an HTTP error.
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Name is too short!'));
		die($output);
	}
	if(!filter_var($useremail, FILTER_VALIDATE_EMAIL)) //email validation
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
		die($output);
	}
	if(strlen($message)<5) //check emtpy message
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Too short message!'));
		die($output);
	}
	
	$to   	= "abhijitscom@gmail.com"; //Replace with recipient email address
	//proceed with PHP email.
	$headers = 'From: '.$useremail.'' . "\r\n" .
	'Reply-To: '.$useremail.'' . "\r\n" .
	'X-Mailer: PHP/' . phpversion();
	
	$sentMail = @mail($to, $subject, $message .'  -'.$username, $headers);
	//$sentMail = true;
	if(!$sentMail)
	{
		$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please contact administrator.'));
		die($output);
	}else{
		$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$username .' Thank you for your email'));
		die($output);
	}
}
?>		

Now you learn how to submit form without page refresh. You can use this application with any form.
Demo
Download

Spread the love
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share