Skip to content
jQuery

AJAX Requests

Use $.ajax, $.get, $.post, and load with promises.

By EZ4Code Team
ajaxhttp

Code

// Promise-based $.ajax
$.ajax({
  url: "/api/users",
  method: "GET",
  dataType: "json"
})
  .done(data => console.log("users", data))
  .fail((xhr, status) => console.error("error", status));

// Shorthands
$.get("/api/posts", posts => render(posts));
$.post("/api/posts", { title: "Hi" }, post => console.log(post));

// JSON-P and loading HTML into an element
$("#result").load("/fragment.html #content");

Explanation

jQuery's $.ajax returns a jqXHR promise supporting done/fail/always callbacks. Shorthand helpers $.get and $.post cover common GET/POST cases, while load() fetches HTML and injects it into the matched element. Set dataType to auto-parse JSON responses.

More jQuery Snippets