jQuery FormValidation and SubmitHandler with AJAX

Form validation is a crucial aspect of web development, ensuring that users submit correct and complete information. In this tutorial, we’ll explore how to implement form validation using the FormValidation library and handle form submission using AJAX.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  • Basic knowledge of HTML, CSS, JavaScript, and jQuery.
  • An understanding of AJAX for handling form submission asynchronously.
  • Access to a web development environment or a web server to test the code.

Setting Up the HTML Form

Let’s start by creating a simple HTML form. This form will have fields for name and email:

<form id="myForm" method="post">
    <div class="mb-3">
        <label for="name" class="form-label">Name:</label>
        <input type="text" class="form-control" id="name" name="name" required>
    </div>
    <div class="mb-3">
        <label for="email" class="form-label">Email:</label>
        <input type="email" class="form-control" id="email" name="email" required>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Adding Form Validation

We’ll use the FormValidation library to add client-side form validation. Make sure you include the necessary CSS and JavaScript files in your HTML:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/formvalidation/0.8.1/css/formValidation.min.css">

.....
.....

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/formvalidation/0.8.1/js/formValidation.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/formvalidation/0.8.1/js/framework/bootstrap.min.js"></script>

Now, initialize form validation using jQuery and FormValidation:

$(document).ready(function() {
    $('#myForm').formValidation({
        framework: 'bootstrap',
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: 'The name is required'
                    }
                }
            },
            email: {
                validators: {
                    notEmpty: {
                        message: 'The email is required'
                    },
                    emailAddress: {
                        message: 'The input is not a valid email address'
                    }
                }
            }
        }
    });
});

Handling Form Submission with AJAX

To handle form submission with AJAX, we’ll intercept the form submission event and use AJAX to send the form data to the server. We’ll use the success.form.fv event provided by FormValidation:

$(document).ready(function() {
    $('#myForm').formValidation({
        // Form validation settings...
    }).on('success.form.fv', function(e) {
        e.preventDefault(); // Prevent the default form submission
        
        var $form = $(e.target); // Get the form element
        var formData = $form.serialize(); // Serialize form data
        
        // Submit form data using AJAX
        $.ajax({
            url: 'submit.php', // Replace 'submit.php' with your server-side script URL
            method: 'POST',
            data: formData,
            success: function(response) {
                // Handle success response
                console.log('Form submitted successfully!');
                console.log(response);
            },
            error: function(xhr, status, error) {
                // Handle error response
                console.error('Error occurred while submitting form:', error);
            }
        });
    });
});

Understanding the Code

In this example:

  • Form Validation with FormValidation and Bootstrap: We utilize the FormValidation library along with the Bootstrap framework to perform client-side form validation. This combination provides a visually appealing and responsive way to validate user input before submission.
  • Intercepting Form Submission with success.form.fv Event: The success.form.fv event is a custom event provided by FormValidation. It allows us to intercept the form submission process after it has been successfully validated. By capturing this event, we can execute custom JavaScript code to handle form submission asynchronously.
  • Preventing Default Form Submission: Within the event handler function, e.preventDefault() is called to prevent the default form submission behavior. This prevents the browser from reloading the page when the form is submitted, allowing us to handle the submission process programmatically via AJAX.
  • Serializing Form Data: To prepare the form data for AJAX submission, we use jQuery’s serialize() method. This method serializes the form data into a URL-encoded string, making it suitable for sending via HTTP POST request.
  • AJAX Submission: We use jQuery’s $.ajax() function to send the serialized form data to the server asynchronously. The url parameter specifies the URL of the server-side script that will handle the form submission (replace 'submit.php' with your actual server-side script URL). We set the method to 'POST' to send the data securely, and the data parameter contains the serialized form data. Additionally, we define success and error callback functions to handle the server’s response, providing feedback to the user accordingly.

By combining these techniques, we create a seamless and user-friendly form submission experience, ensuring that user input is validated and submitted securely without requiring a page reload.

Conclusion

In this tutorial, we’ve learned how to implement form validation using the FormValidation library and handle form submission using AJAX. By combining these techniques, you can create interactive and user-friendly forms that provide immediate feedback to users while submitting data asynchronously.

For more advanced scenarios, you can explore additional features provided by FormValidation, such as custom validators, remote validation, and dynamic field validation here.

To get to know more about other jQuery topics, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply

Share