How to Handle Form Submission Using jQuery Submit

Handling form submissions with the jQuery submit event allows developers to intercept user input before it reaches the server, validate fields on the client side, and submit data asynchronously without refreshing the webpage. This guide explains how to bind the submit event listener to a form element, prevent the browser's default reload behavior, extract input data, and transmit that data using modern AJAX techniques.

Binding the Submit Event

In jQuery, form submission is handled by listening for the submit event on the form element. While the shorthand .submit() method exists, using .on('submit', handler) is the recommended modern approach because it supports dynamic content and provides consistent event handling.

$('#myForm').on('submit', function(event) {
    // Handling logic goes here
});

Preventing the Default Submission

By default, submitting an HTML form causes the browser to reload the page or navigate to the URL specified in the form's action attribute. To handle the submission using JavaScript or AJAX, call event.preventDefault() inside the event handler function to cancel this default behavior.

$('#myForm').on('submit', function(event) {
    event.preventDefault();
    console.log('Form submission intercepted.');
});

Retrieving Form Data

Once the submission is intercepted, you can gather the values from the form controls. jQuery provides built-in methods to format this data easily:

  • $(this).serialize(): Encodes a set of form elements as a query string suitable for URL parameters or standard POST requests (e.g., name=John&email=john%40example.com).
  • $(this).serializeArray(): Encodes form elements into a JavaScript array of objects, where each object contains a name and value property.
  • new FormData(this): A native JavaScript object that handles standard input values as well as file uploads.

Sending Data Asynchronously with AJAX

After gathering the data, you can transmit it to the server using the $.ajax() method. This allows the page to update dynamically without interrupting the user experience.

<form id="contactForm" action="/submit-endpoint" method="POST">
    <input type="text" name="username" placeholder="Username" required>
    <input type="email" name="email" placeholder="Email" required>
    <button type="submit">Send</button>
</form>

<div id="responseMessage"></div>
$(document).ready(function() {
    $('#contactForm').on('submit', function(event) {
        event.preventDefault();

        var form = $(this);
        var formData = form.serialize();

        $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: formData,
            dataType: 'json',
            beforeSend: function() {
                form.find('button[type="submit"]').prop('disabled', true).text('Submitting...');
            },
            success: function(response) {
                $('#responseMessage').html('<p>Form submitted successfully!</p>');
                form[0].reset();
            },
            error: function(xhr, status, error) {
                $('#responseMessage').html('<p>An error occurred: ' + error + '</p>');
            },
            complete: function() {
                form.find('button[type="submit"]').prop('disabled', false).text('Send');
            }
        });
    });
});

This pattern ensures full control over the user experience by enabling validation, providing real-time feedback during network requests, and handling both successful and failed server responses cleanly.