Submit Form without Page Refresh with jQuery AJAX

Ajax is a JavaScript based web development technology used for building asynchronous application. Ajax can send and receive date in the background (without page refreshing or redirecting). We need to use XMLHttpRequest object for working with ajax but jQuery library made it more easy to working with ajax by using jQuery.ajax, jQuery.get, jQuery.post methods.

In this post I have a simple html contact us form example that takes information(name, email, subject and message) from user. When user submit the form data send asynchronously to the server. PHP receives XMLHttpRequest request and process data from server side.


Live Demo Download Source
HTML Markup
Let's take a look at html markup. We have a basic html contact us form
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>HTML Form Submit with jQuery AJAX</title>
</head>
<body>
  <h1>Contact us</h1>
  <form action="" method="post">
    <input type="text" name="name" />
    <input type="mail" name="email" />
    <input type="text" name="subject" />
    <textarea name="message"></textarea>
    <button>Send Mail</button>
  </form>
</body>
</html>

JavaScript and jQuery Code
This jQuery code used for submitting form with ajax request using jQuery.ajax method
<!-- import jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  var form = $('#form'); // contact form
  var submit = $('#submit');  // submit button
  var alert = $('.alert'); // alert div for show alert message

  // form submit event
  form.on('submit', function(e) {
    e.preventDefault(); // prevent default form submit

    $.ajax({
      url: '', // form action url
      type: 'POST', // form submit method get/post
      dataType: 'html', // request type html/json/xml
      data: form.serialize(), // serialize form data 
      beforeSend: function() {
        alert.fadeOut();
        submit.html('Sending....'); // change submit button text
      },
      success: function(data) {
        alert.html(data).fadeIn(); // fade in response data
        form.trigger('reset'); // reset form
        submit.html('Send Email'); // reset submit button text
      },
      error: function(e) {
        console.log(e)
      }
    });
  });
});
</script>

PHP Code
We need to presses user submitted data from server side. This PHP code detects ajax request using HTTP_X_REQUESTED_WITH header request, looks for validation of data and send mail with PHP mail function.
# if request sent using HTTP_X_REQUESTED_WITH
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
  if (isset($_POST['name']) AND isset($_POST['email']) AND isset($_POST['subject']) AND isset($_POST['message'])) {
    $to = 'your@mail.id';

    $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
    $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

    $sent = email($to, $email, $name, $subject, $message);
    if ($sent) {
      echo 'Message sent!';
    } else {
      echo 'Message couldn\'t sent!';
    }
  }
  else {
    echo 'All Fields are required';
  }
  return;
}

/**
 * Email send with headers
 *
 * @return bool | void
 **/
function email($to, $from_mail, $from_name, $subject, $message){
  $header = array();
  $header[] = "MIME-Version: 1.0";
  $header[] = "From: {$from_name}<{$from_mail}>";
  /* Set message content type HTML*/
  $header[] = "Content-type:text/html; charset=iso-8859-1";
  $header[] = "Content-Transfer-Encoding: 7bit";
  if( mail($to, $subject, $message, implode("\r\n", $header)) ) return true; 
}

29 comments:

  1. First of all, great article! This has helped me a ton with AJAX. I was hoping you could elaborate on a part of this. I cannot figure out what is going on here.

    data: form.serialize(),
    ...
    "success: function(data) {
    alert.html(data).fadeIn();"

    I am having such a hard time with this concept, how is the alert being tied to the message being displayed?

    Thanks in advance!

    ReplyDelete
    Replies
    1. HI, the form not working properly in Safari and Android, it send also if the fields are empty.

      Delete
  2. Sorry, but I'm kinda confused on where to set the "To" email address. Am I missing something?

    ReplyDelete
    Replies
    1. Sorry, missed the field in the PHP code.

      But now I'm confused as to where I place this PHP code.

      Delete
    2. Nevermind, I figured it out once I dug through the source files.

      -I'm an idiot :P

      Delete
    3. i have same problem? for me the source is broken.. I am also stupid where do I put the PHP code??

      Delete
  3. Hi, thanks for the nice article, its pretty cool. But I am facing a problem to use it in wordpress. It just shows "Sending..." when I click send email, not showing "message sent". Can anyone help me??

    regards,

    Biplob

    ReplyDelete
  4. I'm confused. There doesn't seem to be any actual validation in this form, so I added my own, but still no luck, it will send a blank email no matter what. So far I can't figure it out, but when it comes to php, jQuery and AJAX, I'm a n00b.

    ReplyDelete
  5. Thanks for good article ; better for learners

    ReplyDelete
  6. Hi! Great tutorial! Is there any way to apply this code using a div button as submit button? I tried different way but I didn't get lucky. Thanks!!

    ReplyDelete
  7. Great stuff! Thanks!
    But I'm having problem using it all the way, after clicking the submit button.
    Would be pleased if someone could take a look to see if I'm missing something.

    http://www.kaoboj.se/test/form.html

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Thanks for your code, I still have the same problem than many people, i can't have the message sent correct after submitting the form, can you fix that?
    many thanks

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
      if (isset($_POST['name'])AND !empty($_POST['name'])AND isset($_POST['email']) AND !empty($_POST['email'])AND isset($_POST['subject']) AND !empty($_POST['subject'])AND isset($_POST['message'])AND !empty($_POST['message'])) {
      if (preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email']))){

      $to = 'your-email';

      $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
      $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
      $subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
      $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
      $sent = email($to, $email, $name, $subject, $message);
      if ($sent) {
      echo 'Message sent!';
      } else {
      echo 'Message couldn\'t sent!';
      }
      }
      else {
      echo 'That is not a valid e-mail address';
      }
      }
      else {
      echo 'All Fields are required';
      }
      return;
      }

      Delete
    2. fix for 'required' and email control

      Delete
  11. hii I have written all query in functions.php. i have written a function to update profile in functions.php.can I call a function in form action url

    ReplyDelete
  12. Mine message is not being delivered though it shows "Message sent!". Please help me out.

    ReplyDelete
  13. Hi,
    Is it possible to use multi form submit using your code?
    Please help me.

    Many Thanks

    ReplyDelete
  14. dịch vụ kế toán thuế tại ninh bình
    dịch vụ kế toán thuế tại vĩnh phúc
    dịch vụ kế toán thuế tại hưng yên
    dịch vụ kế toán thuế tại phú thọ
    dịch vụ dọn dẹp sổ sách kế toán
    dịch vụ dọn dẹp sổ sách kế toán tại thái bình
    dịch vụ dọn dẹp sổ sách kế toán tại phú thọ
    dịch vụ dọn dẹp sổ sách kế toán tại hưng yên
    dịch vụ dọn dẹp sổ sách kế toán tại quận hải dương
    dịch vụ dọn dẹp sổ sách kế toán tại hải phòng
    dịch vụ dọn dẹp sổ sách kế toán tại quận thanh trì
    dịch vụ dọn dẹp sổ sách kế toán tại quận hoàng mai
    dịch vụ dọn dẹp sổ sách kế toán tại quận hai bà trưng
    dịch vụ dọn dẹp sổ sách kế toán tại quận hoàn kiếm
    dịch vụ dọn dẹp sổ sách kế toán tại quận từ liêm
    dịch vụ dọn dẹp sổ sách kế toán tại quận ba đình
    dịch vụ dọn dẹp sổ sách kế toán tại quận tây hồ
    dịch vụ dọn dẹp sổ sách kế toán tại quận đống đa
    dịch vụ dọn dẹp sổ sách kế toán tại bắc ninh
    dịch vụ dọn dẹp sổ sách kế toán tại quận tphcm
    dịch vụ dọn dẹp sổ sách kế toán tại quận cầu giấy
    dịch vụ dọn dẹp sổ sách kế toán tại quận long biên
    dịch vụ dọn dẹp sổ sách kế toán tại quận hà đông
    dịch vụ dọn dẹp sổ sách kế toán tại quận thanh xuân
    dich vu hoan thue gtgt

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. Dapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule yang palsu.
    Slimming capsule yang asli hanya ada di agen herbal tertentu seperti di distro herbal ini, kami merupakan agen herbal terbesar dan sudah di percaya di seluruh penjuru indonesia

    ReplyDelete
  17. Glucoberry merupakan Obat Jerawat Alami Paling Ampuh Dan Cepat, dengan serbuk alami dari glutathione dan colagen dimana khaisatnya mampu untuk memberikan nutrisi pada kulit yang mengalami masalah. Seperti kulit kasar, kulit berminyak, kulit yang berjerawat, kulit yang mengalami penuaan, kerutan di kulit

    ReplyDelete

Go to top