Submit form using AJAX in jQuery

Generally form is submitted to server using specified URL in action attribute but this method refresh web page. So whenever you need to submit form without reloading page then you can use AJAX upload using jQuery.

The jQuery submit() method is useful to handle form submission process or in other way you can customize form uploading. Sometimes we need to validate form before submitting or we need to add custom validation before processing submit or you want to send only some specific data to server rather than all data then you can use jQuery submit method and AJAX.

In this tutorial, we will take example to submit comment using AJAX and jQuery. This comment form will contains name, email and comment text. Here, we will also use bootstrap for some basic formatting.


<!DOCTYPE html>
<ḥhtml>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Simple Comment Form</title>
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
   </head>
   <body>
      <div class="container py-3">
         <div class="row justify-content-center">
            <div class="col-md-6">
               <span class="anchor" id="formLogin"></span>
               <!-- form card login -->
               <div class="card card-outline-secondary">
                  <div class="card-header">
                     <h3 class="mb-0">Comment</h3>
                  </div>
                  <div class="card-body">
                     <form autocomplete="off" class="form" id="commentForm" name="commentForm" role="form" action="comment.php">
                        <div class="form-group">
                           <label for="name">Name</label>
                           <input class="form-control" id="name" name="name" type="text" required>
                        </div>
                        <div class="form-group">
                           <label>Email</label>
                           <input class="form-control" id="email" name="email" type="email" required>
                        </div>
                        <div class="form-group">
                           <label>Comment</label>
                           <textarea class="form-control" id="comment" name="comment" rows="5" required></textarea>
                        </div>
                        <input type="submit" class="btn btn-success btn-lg float-right">
                     </form>
                  </div>
               </div>
            </div>
         </div>
      </div>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer" crossorigin="anonymous"> </script>
      <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script>
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous" > </script>
      <script type="text/javascript" >
          $(document).ready(function(){
              $('#commentForm').submit(function(e){
                  e.preventDefault();
                  
                  var form = $('#commentForm');
                  var actionUrl = form.attr('action');
                  
                  $.ajax({
                      type: "POST",
                      url: actionUrl,
                      data: form.serialize(),
                      dataType: "json",
                      success:function(data){
                          console.log('success');
                      }
                  });
              });
          });
      </script>
   </body>
</html>
   

Here, we have created simple form with name, email and comment as input and defined HTML required attribute for validating user input before submitting form.

In last body section, we have called CDN for bootstrap and jQuery. Lastly, we have defined our form handling functionality.

The script will handle form submit function whenever submit button is clicked. Here, we have used e.preventDefault() function to stop form submitting via reloading. Then we have created variable and store form element and defined another variable to get and store action URL.

At last, we have called AJAX function and passed all form data using serialize() function to AJAX request and in response we just have printed success message to console.

Conclusion

In this article, we have created simple form and submit it using jQuery and AJAX. Now, most of application required to use AJAX at some point. Major web application like LinkedIn and Facebook use AJAX and jQuery to load data or handle posting and comments.


Share your thoughts

Ask anything about this examples