Submit Form Without Page Refresh Using Ajax, jQuery and PHP


Demo Download

In this tutorial, i will explain how to submit contact form without page refresh using AJAX, jQuery and PHP. We all have seen that when we submit any web form or contact form, it takes few seconds to submit without refreshing the web page.

AJAX has the ability to submit form without page refresh. We will also use AJAX here along with jQuery and PHP. Although you can do anything with the form submission, in here we will send a simple email to website admin.

Steps to Creating Submit Form Without Page Refresh Using Ajax, jQuery and PHP

To create a user friendly contact form we will need to follow the below steps:

  1. Create a HTML Form Page
  2. Include Bootstrap Library
  3. Include jQuery Library
  4. jQuery Form Validation & AJAX Method
  5. Create an AJAX Action Page

1. Create a HTML Form Page

First we will create a simple contact form to get information from user. Create a page with name index.php  and paste the below code in it. We are getting following information.

Name, Email and Message

<form name="ContactForm" method="post" action="">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea name="message" class="form-control" id="message">
</textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

<div class="message_box" style="margin:10px 0px;">
</div>

After the simple contact form, we also created an empty div having class message_box, we will use this div to display all errors and successful message.

2. Include Bootstrap Library

To give it simple and quick style we are using here Bootstrap library, so lets include Bootstrap library in the head section of your web page.

<link rel="stylesheet" href="css/bootstrap.min.css">

3. Include jQuery Library

Since we will be using jQuery and AJAX therefore we need to include jQuery Library before closing of </body> tag.

<script src="js/jquery.min.js"></script>

You can download the both library files from the download button which is available in the beginning and bottom of this tutorial.

4. jQuery Form Validation & AJAX Method

Now we also need to validate our web form data, so we will make sure that all input fields are filled and entered email address is valid. After that we will also use AJAX method to submit form without refreshing the page.

<script>
$(document).ready(function() {
   var delay = 2000;
   $('.btn-default').click(function(e){
   e.preventDefault();
   var name = $('#name').val();
   if(name == ''){
   $('.message_box').html(
   '<span style="color:red;">Enter Your Name!</span>'
   );
   $('#name').focus();
   return false;
   }
		
   var email = $('#email').val();
   if(email == ''){
   $('.message_box').html(
   '<span style="color:red;">Enter Email Address!</span>'
   );
   $('#email').focus();
   return false;
   }
   if( $("#email").val()!='' ){
   if( !isValidEmailAddress( $("#email").val() ) ){
   $('.message_box').html(
   '<span style="color:red;">Provided email address is incorrect!</span>'
   );
   $('#email').focus();
   return false;
   }
   }
			
   var message = $('#message').val();
   if(message == ''){
   $('.message_box').html(
   '<span style="color:red;">Enter Your Message Here!</span>'
   );
   $('#message').focus();
      return false;
   }	
					
   $.ajax
   ({
   type: "POST",
   url: "ajax.php",
   data: "name="+name+"&email="+email+"&message="+message,
   beforeSend: function() {
   $('.message_box').html(
   '<img src="Loader.gif" width="25" height="25"/>'
   );
   },		 
   success: function(data)
   {
   setTimeout(function() {
   $('.message_box').html(data);
   }, delay);
   }
   });
   });
			
});
</script>

Email Verification Function

<script>
//Email Validation Function	
function isValidEmailAddress(emailAddress) {
    var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
    return pattern.test(emailAddress);
};
</script>

As you can see in the above script that we are doing simple validation, it is very simple script which is just checking if name is empty then focusing its cursor on name field, and also showing error in the .message_box div, same we are doing for email and for message fields. We are additionally checking email that is it valid or not by using the above isValidEmailAddress()  function.

When all fields are filled out and user press submit button, AJAX sends the all input fields data to ajax.php page which will simply send the email to the web admin.

5. Create an AJAX Action Page

Create a page with name ajax.php, this will send email to web admin using simple PHP mail function. Although the prefer way to send email in PHP using PHPMailer but i am using here mail function to keep this tutorial simple, i will suggest you all use PHPMailer. Copy and paste the below script in ajax.php

<?php
if ( ($_POST['name']!="") && ($_POST['email']!="")){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = "[email protected]";
$subject = "AllPHPTricks Contact Form Email";
$message = "<p>New email is received from $name.</p>
<p>$message</p>";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: <".$email.">" . "\r\n";
$sent = mail($to,$subject,$message,$headers);
if($sent){
	echo "<span style='color:green; font-weight:bold;'>
	Thank you for contacting us, we will get back to you shortly.
	</span>";
}
else{
	echo "<span style='color:red; font-weight:bold;'>
	Sorry! Your form submission is failed.
	</span>";
	}
}
?>

Make sure to change your email in the above script in variable $to = “[email protected]”;

I hope you all can implement this contact form easily on your website, if anyone still have any problem then you can leave your problem in the below comment section.

Demo Download

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
  1. Hi Sir, I am trying to use your tutorial about sending contact form html by email but it doesn’t work for me. I downloaded the code and I used it. the only thing I change in your code is the email address. I want to know if there is something I need to do again. thank you

  2. Ive tried this form within a php script im running and i find that instead of the return passing thru the success or fail message to the message_box it instead reloads the whole webpage within the div.

    any ideas why this would be happening and how to resolve?

    1. Dear Steve, I would suggest you first check that why are you getting in response using console.log() function, if you are getting the correct response then you should check your PHP script which is returning the success message.

  3. Hi, Javed! Great contact form! I have tried some similar contact forms but the other forms don’t work with Firefox (because of the lack of proper e.preventDefault(); code. Your form works well in Chrome, Firefox, Opera, and the new Chromium-based IE. Good job!

    One tiny request: Could you provide a version that does not use the Bootstrap CSS code? My personal website I want to integrate the form into do not use Bootstrap.

    Second tiny request: Could you provide a version that has a simple anti-spam protection in it, such as a “add two numbers together” anti-spam protection?

    Again, great job!

    – Brock Wood

  4. Hi, Javed,
    I have some issues there,

    1. After submit form, form data is presence there, i think it should be reset after form submission.
    2. Not getting thank you message

    1. Hi Tarun,

      If you want to empty input fields so you can do it using jQuery, after successful form submission set value of these fields to null.

      If you are not getting thank you message, may be your form is not submitting, make sure that jQuery library is added, you can debug to code using alert.

  5. Hi Javed, thank very much for this tutorial,I tried the code it is worked perfectly. I have a quick question: If I have two forms and I would like to store the information of the first form (after hitting send button) on the second form before final submission, how can I implement this? (Without page refresh). For example the fist form has checkin, checkout, no.pax and I want after hitting the Inquiry button the user asked for further info on the same form section and after filling the second form the whole information sent to database and email!!!?

  6. Hello Javed,
    Thank you for the tutorial.
    So I adapted you code to work with my form but the PHP script isn’t sending the email. Only the validation works.

    Aside simple errors do you know any reasons why this might be so?
    This https://codepen.io/obaitan/pen/XWjVyRo is the code. Please see the PHP script in the CSS area(!).

    Anything you can suggest will be appreciated. Thank you!

  7. My coder is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs. But he’s tryiong none the less.
    I’ve been using WordPress on several websites for about a year and am worried about
    switching to another platform. I have heard good things about blogengine.net.
    Is there a way I can import all my wordpress content into it?
    Any kind of help would be greatly appreciated!

  8. Thanks for the tutorial. I live in Brazil.
    Javed…
    I followed the guidelines as you mentioned. but is returning the following error:
    “Warning: mail () [function.mail]: SMTP server response: 530 5.7.0 Must issue a STARTTLS command first. V1sm34006057qkj.19 – gsmtp in C: \ Program Files (x86) \ EasyPHP-5.3.2 \ www \ ajax.php online 21
    Sorry! Your form submission is failed. ”
    I am using EasyPhp 5.3.2 local server.
    Thank you in advance.

  9. sir Shadi.com jaisa register form kaise create karege plz write artical .plz have any link provide me .

    1. Sapana there are varieties of forms that are using stylish CSS and jquery and AJAX, hope you can find good tutorials on Google, currently i do not have any fancy form tutorial.

  10. Javed ji, I stuck with a problem. My search.php page having two buttons, one button for fetching data from two different dates and other one for deleting particular unwanted record. I have placed value “value=”” for search button which retains the entered values even after submission. Coming to delete button, all data fetched is vanishing after submission of the delete button. Deleting the record is working but I want to show the user the remaining records after delete. Kindly guide me sir.

    1. I will suggest you to learn AJAX with more examples. If you want to show data after deleting some data so first you will need to delete data and then get the remaining data using MySQL query, you will need to perform this all using AJAX, i have created an example here to submit form without refresh page using ajax and jQuery, i think you should try to learn more example how to use ajax to get the data. Such as you can also check my tutorial here https://www.allphptricks.com/dynamic-dependent-select-box-using-jquery-and-ajax/ i explain how to work with dynamic dependent selectbox, this is another example of ajax. Hope this help you.

  11. What i don’t understood is actually how you’re now not really much more well-liked than you may
    be right now. You’re so intelligent. You already know thus considerably with regards to this topic, made
    me in my view consider it from so many various angles. Its like men and women don’t seem
    to be fascinated unless it’s something to accomplish with Lady gaga!
    Your personal stuffs excellent. At all times handle it up!

  12. Hi,

    Thanks for the tutorial!

    I would like to send email using PHPMailer can you please guide me.

    How it should integrate in current tutorials.

    Please advice!

    Regards,
    Viren

  13. Everything is very open with a very clear clarification of
    the challenges. It was truly informative. Your website is very
    useful. Thank you for sharing!

  14. Do you mind if I quote a few of your articles as long as I
    provide credit and sources back to your blog? My blog site is in the exact same area of
    interest as yours and my visitors would really benefit from a lot of
    the information you provide here. Please let me know if this okay with you.
    Regards!

Leave a Reply

Your email address will not be published. Required fields are marked *