SyntaxStudy
Sign Up
jQuery jQuery AJAX Form Submission
jQuery Intermediate 6 min read

jQuery AJAX Form Submission

Submitting forms without a page reload is one of the most practical uses of AJAX. jQuery makes this ergonomic with .serialize() and .serializeArray() helpers that encode form data automatically.

Serializing Form Data

$('#form').serialize() encodes all successful form controls as a URL-encoded query string: name=Jane&email=jane%40example.com. This string is ready to pass directly to $.post() or as the data option of $.ajax().

Sending as JSON

To send form data as JSON, convert it with .serializeArray() — which returns an array of { name, value } pairs — and reduce it to a plain object before passing to JSON.stringify(). Set contentType: 'application/json' in the $.ajax() options.

  • .serialize() — URL-encoded string
  • .serializeArray() — array of name/value objects
  • Set contentType: 'application/json' for JSON APIs
  • Validate client-side before sending to reduce server load

Always prevent the default form submission with event.preventDefault() in the submit handler, or the browser will perform a full page reload before your AJAX call can complete.

Example
$('#signup-form').on('submit', function (e) {
    e.preventDefault();

    var $btn  = $('#submit-btn').prop('disabled', true).text('Saving…');
    var $form = $(this);

    $.ajax({
        url        : '/api/signup',
        method     : 'POST',
        contentType: 'application/json',
        data       : JSON.stringify(
            $form.serializeArray().reduce(function (obj, f) {
                obj[f.name] = f.value;
                return obj;
            }, {})
        )
    })
    .done(function (resp) {
        $('#status').text(resp.message).addClass('success');
    })
    .fail(function (xhr) {
        $('#status').text(xhr.responseJSON.error).addClass('error');
    })
    .always(function () {
        $btn.prop('disabled', false).text('Submit');
    });
});
Pro Tip

Always call e.preventDefault() first in a form submit handler, before any async call, to stop the page from reloading.