arrow_back
Back

jQuery AJAX: $.ajax, shorthand methods, and JSON

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

open_in_new Documentation .

Create an AJAX request (default method is GET):

let ajax = $.ajax({
   url: "/index.php",
   data: {
       name : "Andrew",
       weight : 85
   }
});

Using callbacks:

$.ajax({
    url: "/index.php",
    data: {
        name : "Andrew",
        weight : 85
    },
    success: function() {
        alert("success");
    },
    error: function() {
        alert("error");
    },
    complete: function() {
        alert("complete");
    }
});

Or:

ajax.done(function() {
    alert( "success" );
});

ajax.fail(function() {
    alert( "error" );
});

ajax.always(function() {
    alert( "complete" );
});

Submit a form via AJAX

Collect fields with serialize() and POST to the form’s action:

$('#js-sign-up-form').on('submit', function (e) {
    const form = $(this);
    const data = form.serialize();

    $.post({
        url: form.attr('action'),
        data: data,
        success: function (response) {
            // ...
        }
    });

    e.preventDefault();
});

Note on concurrency

In practice, AJAX requests often run one after another rather than truly in parallel (browser connection limits and how calls are issued).

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

jQuery objects: selectors, chaining, and the jQuery collection

arrow_forward