Lessons in this course (10)
5. AJAX with $.ajax, $.get, $.post and deferreds
Intermediate★ Must knowLesson 5 of 10
js
$.ajax({
url: "/api/orders",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ customerId: 5, items: [{ productId: 1, qty: 2 }] }),
dataType: "json",
headers: { RequestVerificationToken: $("input[name='__RequestVerificationToken']").val() },
timeout: 10000,
})
.done(order => showToast(`Order ${order.id} created`))
.fail((xhr, status, err) => showError(xhr.responseJSON?.title ?? err))
.always(() => $("#spinner").hide());
$.get("/api/products", { category: "laptops" }).done(render);
$.getJSON("/api/products/5").done(p => $("#name").text(p.name));
$("#result").load("/Orders/Summary #summaryPanel"); // load HTML fragment into element
// Parallel requests
$.when($.getJSON("/api/user"), $.getJSON("/api/orders")).done((userRes, ordersRes) => {
const user = userRes[0], orders = ordersRes[0];
});
// Global AJAX events
$(document).ajaxStart(() => $("#spinner").show()).ajaxStop(() => $("#spinner").hide());jqXHR objects are thenable (Promises/A+ compatible since 3.0), so they work with await. .success/.error/.complete callbacks were removed in 3.0 — use .done/.fail/.always.