How to perform jQuery Callback after submitting the form?


Nowadays, every website contains at least a single form, such as a contact form, application form, etc. It is also required to notify users when the form is submitted successfully or with errors so that users can take action again.

In JQuery, we can use the submit() method to call the callback function after submitting the form. However, we can also save form data to the database in the callback functions. So, there can be many use cases where we must call the callback function after submitting the form to perform the particular operations.

Syntax

Users can follow the syntax below to call the callback function after submitting the form in JQuery.

$("#form_id").submit(function (event) {
   event.preventDefault();
   // code for the callback function
});

In the above syntax, we accessed the form in JQuery and executed the submit() method on the form. Also, we passed the callback function as a parameter of the submit() method.

Let’s learn to use the callback function with submit() method in JQuery via different examples.

Example 1 (Basic Form Submission Callback)

In the example below, we demonstrated the basic submission callback in JQuery. Here, we created the form to take the food input data, and the form id is the ‘test_form’.

In jQuery, we accessed the form using its id and executed the submit() method. Also, we passed the anonymous callback function as a parameter of the submit() method. In the callback function, we add the ‘form submitted successfully’ message to the web page.

Users can enter the input data and click the submit button to submit the form. After that, they will see a message on the web page.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"> </script>
</head>
<body>
   <h3> Calling the <i> JQuery's callback function </i> after submitting the form </h3>
   <form id = "test_form">
      <input type = "text" name = "food_name" placeholder = "Enter food name" />
      <input type = "text" name = "food_type" placeholder = "Enter food type" />
      <input type = "text" name = "food_price" placeholder = "Enter food price" />
      <input type = "submit" value = "Submit" />
   </form>   <br>
   <div id = "result"> </div>
   <script>
      $(document).ready(function () {
         // Callback function will be called after submitting the form.
         $("#test_form").submit(function (event) {
            event.preventDefault();
            $("#result").html("Form submitted successfully");
         });
      });
   </script>
</body>
</html>

Example 2 (Asynchronous Form Submission with AJAX)

In the example below, we demonstrated the asynchronous form submission. We created the form to take the blog post data. We take the post title, post body, author, and scheduled date for the post from users.

When users click the submit button, it will execute the callback function of the submit() method. In the callback function, we used the ‘fetch’ API to make a ‘POST’ request to the https://dummyjson.com/posts/add URL.

We passed the URL as the first parameter of the fetch(), and an object containing the method, header, and body as a second parameter. Also, we print the response on the web page.

In the output, users can enter the post data in the form and click the submit button to check the response.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"> </script>
</head>
<body>
   <h3> Calling <i> jQuery's callback function </i> after submitting the form </h3>
   <form id = "post_form">
      <input type = "text" name = "post_title" id = "post_title" placeholder = "Post Title" /><br> <br>
      <input type = "text" name = "post_body" id = "post_body" placeholder = "Post Body" /> <br> <br>
      <input type = "text" name = "author" id = "author" placeholder = "Author" /> <br> <br>
      <input type = "date" name = "schedule_date" id = "schedule_date" placeholder = "Schedule Date" />  <br> <br>
      <input type = "submit" value = "Submit" />
   </form>    <br>
   <div id = "result"> </div>
   <script>
      $(document).ready(function () {
         $("#post_form").submit(function (event) {
            event.preventDefault();
            fetch('https://dummyjson.com/posts/add', {
               method: 'POST',
               headers: { 'Content-Type': 'application/json' },
               body: JSON.stringify({
                  title: $('#post_title').val(),
                  body: $('#post_body').val(),
                  author: $('#author').val(),
                  scheduleDate: $('#schedule_date').val(),
                  userId: 5,
               })
            })
            .then(res => res.json())
            .then(data => {
               // Display response data in the 'result' div
               $('#result').text(JSON.stringify(data, null, 2));
            });
         });
      });
   </script>
</body>
</html>

Example 3 (Validating the form on submission)

In the example below, we demonstrated to validate the form by calling the callback function on form submission. Here, the form takes the printer data.

In jQuery, we show the validation message if any input value is empty. Also, if the price of the printer is less than 10000, we show the validation message accordingly.

In the output, users can enter a price less than 10000 in the input field and click the submit button to see the validation message.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"> </script>
</head>
<body>
   <h3> Calling <i> jQuery's callback function </i> after submitting the form </h3>
   <form id = "printer_form">
      <lable for = "printer"> Printer </lable>
      <input type = "text" id = "printer" name = "printer" placeholder = "Printer"> <br> <br>
      <lable for = "price"> Price </lable>
      <input type = "number" id = "price" name = "price" placeholder = "Price"> <br> <br>
      <input type = "submit" value = "Submit" />
   </form>  <br>
   <div id = "result"> </div>
   <script>
      $(document).ready(function () {
         $("#printer_form").submit(function (event) {
            event.preventDefault();
            if ($("#printer").val() == "" || $("#price").val() == "") {
               $('#result').html("Please fill all the fields");
            } else if ($("#price").val() < 10000) {
               $('#result').html("Price is very low");
            } else {
               $('#result').html("Form submitted successfully");
            }
         });
      });
   </script>
</body>
</html>

Conclusion

We learned to execute the callback function after submitting the form in jQuery. If we use the submit input, we can use the submit() method in jQuery to execute the callback function. If we use the normal button to submit the form, we can call the function when users click the button.

Also, we learned different use cases where we could call the callback function after submitting the form. In the first example, we executed a callback function to notify users about a form submission. In the second example, we post data to a particular URL; in the third example, we use a callback function for the form validation.

Updated on: 26-Jul-2023

939 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements