jQuery - jQuery AJAX
1) What is AJAX (in jQuery)?
AJAX (Asynchronous JavaScript and XML) lets you send/receive data from a server without reloading the page. jQuery wraps XMLHttpRequest
with a simpler API, automatic parsing, and a promise-like return (jqXHR
).
Typical uses: loading partial HTML, submitting forms in the background, fetching JSON for UI updates.
2) Core APIs
a) The workhorse: $.ajax(options)
$.ajax({
url: "/api/users/42",
method: "GET", // alias: type
data: { verbose: true }, // for query/body depending on method
dataType: "json", // expected response: json | text | html | xml | script | jsonp
timeout: 10000, // ms
success(res, status, xhr) { /* handle data */ },
error(xhr, status, err) { /* handle error */ },
complete(xhr, status) { /* always runs */ }
});
b) Shorthands
-
$.get(url[, data][, success][, dataType])
-
$.post(url[, data][, success][, dataType])
-
$("#el").load(url[, data][, complete])
– fetch and inject HTML -
$.getJSON(url[, data][, success])
– convenience for JSON GET -
$.getScript(url[, success])
– load and execute a script
c) Global defaults
$.ajaxSetup({ cache: false, timeout: 10000, dataType: "json" });
3) Important $.ajax
options (what they do)
-
url – endpoint to call.
-
method/type –
"GET"
,"POST"
,"PUT"
,"DELETE"
, … -
data – object/query string/FormData to send.
-
dataType – how to parse the response (
"json"
auto-parses to object). -
contentType – request body type (default
"application/x-www-form-urlencoded; charset=UTF-8"
). Use"application/json"
when sending JSON. -
processData –
false
to prevent jQuery from converting data to a query string (needed forFormData
). -
headers – custom request headers.
-
xhrFields – e.g.,
{ withCredentials: true }
for cookies across domains (if CORS allows). -
crossDomain – hint for cross-origin requests.
-
timeout – fail if no response in N ms.
-
beforeSend(xhr, settings) – last chance to modify request (e.g., add auth header).
-
success / error / complete – callbacks.
-
cache – for GET;
false
appends a cache-buster.
Avoid async: false
(sync XHR is deprecated).
4) The return value: jqXHR
(Deferred/Promise-like)
Every $.ajax()
call returns a jqXHR
you can chain:
const req = $.ajax({ url: "/api/items", dataType: "json" });
req.done(data => render(data))
.fail((xhr, status, err) => showError(status))
.always(() => hideSpinner());
// Cancel if needed:
req.abort();
fail
arguments: (jqXHR, textStatus, errorThrown)
5) Sending data
a) Query params / form style
$.get("/search", { q: "laptop", page: 2 });
b) JSON body
$.ajax({
url: "/api/todos",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ title: "Buy milk" }),
dataType: "json"
});
c) From forms
const body = $("#myForm").serialize(); // "name=Ana&age=32"
const arr = $("#myForm").serializeArray(); // [{name:"name",value:"Ana"}, ...]
d) File upload (FormData)
const fd = new FormData($("#uploadForm")[0]);
$.ajax({
url: "/upload",
method: "POST",
data: fd,
processData: false, // don't stringify
contentType: false // let browser set multipart boundary
});
6) Receiving & parsing
Choose dataType so jQuery parses for you:
-
"json"
→ JS object/array -
"text"
→ raw string -
"html"
→ raw HTML (you can inject into DOM) -
"xml"
→ XMLDocument
-
"script"
→ executes returned JS -
"jsonp"
→ legacy cross-domain technique (GET only; avoid for security)
7) Global AJAX events (useful for loaders/logging)
Attach to document
:
$(document)
.ajaxStart(() => $("#spinner").show())
.ajaxStop(() => $("#spinner").hide())
.ajaxError((e, xhr, settings, err) => logError(err));
Other events: ajaxSend
, ajaxSuccess
, ajaxComplete
.
8) Robust error handling
$.ajax({ url: "/api/profile", dataType: "json" })
.done(data => updateUI(data))
.fail((xhr, status) => {
const msg = xhr.responseJSON?.message || xhr.status + " " + xhr.statusText;
alert("Request failed: " + msg);
})
.always(() => cleanup());
Check xhr.status
(e.g., 400/401/403/404/500) and handle accordingly.
9) CORS & cross-site calls
Server must send proper CORS headers (Access-Control-Allow-Origin
, etc.).
If you need cookies/auth across domains:
$.ajax({
url: "https://api.example.com/data",
xhrFields: { withCredentials: true }
});
JSONP (dataType: "jsonp"
) is legacy; prefer proper CORS.
10) Caching & performance tips
-
For dynamic GETs you can set
cache: false
; for static assets, leave caching on. -
Debounce rapid triggers (e.g., on keyup) to reduce requests.
-
Abort previous in-flight requests when issuing a new one (type-ahead UIs).
-
Batch requests server-side when possible.
Example debounce + abort:
let pending;
const search = _.debounce(term => {
if (pending) pending.abort();
pending = $.get("/search", { q: term })
.done(showResults)
.always(() => pending = null);
}, 300);
$("#q").on("input", e => search(e.target.value));
11) Security essentials
-
Always use HTTPS.
-
Include CSRF tokens on state-changing requests (POST/PUT/PATCH/DELETE).
-
Validate/sanitize data server-side; never trust client input.
-
Avoid
eval
/script
dataType unless you fully trust the source.
12) Practical patterns
a) Load partial HTML into a container
$("#details").load("/orders/123/summary", () => initTooltips());
b) Submit a form via AJAX with UI feedback
$("#profileForm").on("submit", function (e) {
e.preventDefault();
const btn = $("#saveBtn").prop("disabled", true);
$.ajax({
url: this.action,
method: this.method,
data: $(this).serialize(),
dataType: "json"
})
.done(({ message }) => toast(message))
.fail((xhr) => showError(xhr.responseText))
.always(() => btn.prop("disabled", false));
});
c) Set site-wide defaults once
$.ajaxSetup({
timeout: 12000,
headers: { "X-App-Version": "1.4.0" }
});
13) jQuery AJAX vs fetch
(quick mapping)
// jQuery
$.ajax({ url:"/api/items", method:"POST", data: JSON.stringify(obj),
contentType:"application/json", dataType:"json" })
.done(handle).fail(handleErr);
// fetch (native)
fetch("/api/items", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(obj)
})
.then(r => r.json())
.then(handle)
.catch(handleErr);