Submit Forms with jQuery AJAX

Introduction

When it comes to enhancing the user experience on web applications, asynchronous calls via AJAX have made a huge improvement. One area where AJAX really shines is in form submissions. In this Byte, we'll explore how to use jQuery AJAX to submit forms, thereby creating a seamless user experience.

What is AJAX?

AJAX stands for "Asynchronous JavaScript and XML". It's a set of web development techniques that allows a web page to update and retrieve data from a server asynchronously, without blocking the display of the page. In essance, AJAX allows web pages to be updated asynchronously by sending or receiving data with a server, without needing page reloads.

Why use AJAX for Form Submissions?

Traditionally, when a form is submitted, the page reloads and displays the updated information. This can be a jarring experience for users and can also be inefficient, especially if only a small part of the page needs to be updated. AJAX allows us to update only the necessary parts of a web page, without requiring a full page refresh. This results in a smoother user experience and can also save on bandwidth.

Setting up the HTML Form

Before we can use AJAX to submit a form, we need a form to work with. For this tutorial, we'll use a simple contact form. Here's the HTML code for it:

<form id="contactForm">
    <label for="name">Name:</label><br>
    <input type="text" id="name" name="name"><br>
    <label for="email">Email:</label><br>
    <input type="text" id="email" name="email"><br>
    <input type="submit" value="Submit">
</form>

This form has two fields: name and email. The important thing to note here is the id attribute of the form, which we'll use to target the form with jQuery.

Writing the jQuery AJAX Call

With our form set up, we can now write the jQuery AJAX call to handle the form submission. Here's the code to do it:

$('#contactForm').submit(function(event) {
    event.preventDefault();

    var form_data = $(this).serialize();

    $.ajax({
        url: 'submit_form.php',
        type: 'POST',
        data: form_data,
        success: function(response) {
            // Handle the response
        },
        error: function(error) {
            // Handle the error
        }
    });
});

In this code, we first prevent the form from being submitted the traditional way using event.preventDefault(). We then serialize the form data into a query string using $(this).serialize(). Finally, we make the AJAX call using $.ajax(), passing in the URL to submit the form to, the HTTP method to use (POST in this case), the form data, and two callbacks for handling success and error scenarios.

Form Submission with AJAX

So let's get into how you can submit a form using AJAX. The primary purpose of AJAX is to improve the user experience by updating parts of a web page without reloading the whole page. For this, we will use the jQuery $.ajax() method.

Here's an example of how you can use AJAX to submit a form:

$("form").submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
        type: "POST",
        url: form.attr('action'),
        data: form.serialize(),
        success: function(data){
            console.log('Submission was successful.');
            console.log(data);
        },
        error: function(data){
            console.log('An error occurred.');
            console.log(data);
        },
    });
});
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

In this example, when the form is submitted, the AJAX call is made. If the AJAX call is successful, the success function is executed, otherwise, the error function is executed.

Error Handling in AJAX Form Submission

Error handling is an important part of any remote request. The AJAX method provides several options for handling different kinds of errors. In the previous example, we used the error callback function to handle the errors.

You can also handle specific HTTP status codes using the statusCode object, like so:

$.ajax({
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    statusCode: {
        404: function() {
            alert('page not found');
        }
    },
    success: function(data){
        console.log('Submission was successful.');
        console.log(data);
    },
    error: function(data){
        console.log('An error occurred.');
        console.log(data);
    },
});

Here, if the AJAX call returns a 404 status code, the function inside the statusCode object will be executed.

Using AJAX with Other Form Elements

You can use AJAX with other form elements as well. For instance, you can use AJAX to update a <select> dropdown list based on another dropdown list's selection. Here's an example:

$('select[name="country"]').change(function() {
    var countryID = $(this).val();
    if(countryID) {
        $.ajax({
            url: '/getStates/'+countryID,
            type: "GET",
            dataType: "json",
            success: function(data) {
                $('select[name="state"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="state"]').append('<option value="'+ key +'">'+ value +'</option>');
                });
            }
        });
    }else{
        $('select[name="state"]').empty();
    }
});

Now, when a country is selected, the AJAX call is made to the server to fetch the states of the selected country.

Conclusion

In this Byte, we've covered how to submit a form using AJAX, how to handle errors in AJAX form submission, and how to use AJAX with other form elements. By using asynchronous calls like this, we can improve the user experience by updating parts of a web page without reloading the whole page. Remember, error handling is a crucial part of any AJAX request to ensure the robustness of your application.

Last Updated: August 26th, 2023
Was this helpful?
Project

React State Management with Redux and Redux-Toolkit

# javascript# React

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup
Uchechukwu Azubuko
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms