Submit form using AJAX in jQuery

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

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

In this tutorial, we will take examples of submitting comments using AJAX and jQuery. This comment form will contain the 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 a simple form with name, email, and comment as input and defined the HTML required attribute for validating user input before submitting the form.

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

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

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

Conclusion

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