jQuery AJAX — Complete Async Requests & API Calls Guide
jQuery AJAX lets you send and receive data from a server without refreshing the page, enabling dynamic content loading, form submissions, and API interactions that feel seamless to the user.
What You’ll Learn
- How to load HTML content dynamically with
.load() - How to send GET and POST requests with
$.get()and$.post() - How to fetch JSON data with
$.getJSON() - How to configure full AJAX requests with
$.ajax() - How to handle errors, timeouts, and loading states
- How to serialize forms and work with JSONP
Why jQuery AJAX Matters
AJAX is what makes modern web apps feel instant. Instead of waiting for a full page reload, AJAX fetches only the data that changed — like refreshing a single comment instead of reloading the entire article. Think of it like ordering food at a restaurant instead of going to the grocery store to cook every meal. In DodaTech’s Durga Antivirus Pro, AJAX loads real-time threat feeds, submits scan requests, and fetches dashboard statistics — all without a single page refresh.
AJAX Learning Path
flowchart LR
A[jQuery Events] --> B[jQuery DOM Manipulation]
B --> C[jQuery AJAX: You Are Here]
C --> D[.load() - HTML]
C --> E[$.get()/$.post() - Data]
C --> F[$.getJSON() - APIs]
C --> G[$.ajax() - Full Control]
D --> H[Dynamic Web Apps]
E --> H
How AJAX Works
The browser sends a request to a server in the background. When the server responds, jQuery automatically passes the data to your callback function. Meanwhile, the user keeps interacting with the page — there’s no white flash, no page reload.
Analogy: AJAX is like asking a librarian to find a book while you wait at the table. The librarian (AJAX request) goes to the stacks (server), finds the book (data), and brings it back to you (callback), while you keep reading other books (using the page).
.load() — Simplest AJAX
.load() fetches HTML from a URL and inserts it directly into the matched element:
// Load entire page into #result
$("#result").load("page.html");
// Load a specific fragment (add selector after URL)
$("#result").load("page.html #content");
// With callback
$("#result").load("page.html", function(response, status, xhr) {
if (status === "success") {
console.log("Content loaded successfully");
} else {
console.log("Error: " + xhr.status);
}
});
// With data (POST request)
$("#result").load("api.php", { id: 42, action: "get" });
// Real-world: refresh comments section
$("#comments").load("article.php #comments");Why .load() is useful: It’s the quickest way to fetch and display HTML. No need to parse or manipulate — the HTML goes straight into the DOM.
$.get() and $.post()
These shorthand methods send GET and POST requests:
// GET request — retrieve data
$.get("api/users", function(data) {
console.log("Users:", data);
});
// GET with parameters
$.get("api/users", { page: 2, limit: 10 }, function(data) {
console.log(data);
});
// POST request — send data to create/update
$.post("api/login", {
username: "alice",
password: "secret"
}, function(response) {
console.log("Login response:", response);
});Promise Interface
Both methods return a promise, enabling cleaner chaining:
$.post("api/users", { name: "Alice", age: 30 })
.done(function(data) {
console.log("User created:", data);
})
.fail(function(xhr) {
console.log("Error:", xhr.responseText);
})
.always(function() {
console.log("Request completed (success or failure)");
});Always handle errors! Without .fail(), a failed request silently does nothing.
$.getJSON()
Shortcut for fetching JSON data via GET:
$.getJSON("https://api.example.com/users", { limit: 5 }, function(data) {
$.each(data, function(i, user) {
$("#userList").append("<li>" + user.name + "</li>");
});
});
// With promise chain
$.getJSON("api/stats")
.done(function(data) {
$("#visitors").text(data.visitors);
$("#sales").text(data.sales);
})
.fail(function() {
$("#stats").text("Failed to load statistics");
});$.ajax() — Full Configuration
When you need full control over the request, use $.ajax():
$.ajax({
url: "api/users",
method: "GET",
data: { page: 1, limit: 20 },
dataType: "json", // Expected response type
timeout: 5000, // 5 second timeout
headers: {
"Authorization": "Bearer token123",
"X-CSRF-Token": csrfToken
},
success: function(response) {
console.log("Data:", response);
},
error: function(xhr, status, error) {
console.log("Error:", error);
},
complete: function() {
console.log("Request finished");
}
});Key $.ajax() Options
$.ajax({
url: "api/data",
method: "POST", // GET, POST, PUT, DELETE, PATCH
// Data formats
data: { name: "Alice" }, // Object → query string
data: JSON.stringify(obj), // JSON string (set contentType too)
// Content type
contentType: "application/x-www-form-urlencoded", // Default for forms
contentType: "application/json", // For JSON body
// Response format
dataType: "json", // json, xml, html, script, text, jsonp
// Before sending
beforeSend: function() {
$("#loader").show(); // Show loading indicator
},
// Progress (for file uploads)
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var pct = e.loaded / e.total * 100;
$("#progress").val(pct);
}
});
return xhr;
}
});Combining Multiple Requests with $.when()
Wait for all requests to complete before proceeding:
$.when(
$.get("api/users"),
$.get("api/posts"),
$.get("api/comments")
).done(function(users, posts, comments) {
console.log("All 3 requests completed");
console.log("Users:", users[0]); // First argument is the data
console.log("Posts:", posts[0]);
}).fail(function() {
console.log("One of the requests failed");
});This is like ordering from three different restaurants and waiting until all deliveries arrive before eating.
Serializing Forms
Convert form data into a format suitable for AJAX:
// Serialize to query string
var data = $("form").serialize();
// "name=Alice&email=alice%40test.com&age=30"
// Serialize to array of objects
var data = $("form").serializeArray();
// [{name: "name", value: "Alice"}, {name: "email", value: "alice@test.com"}]
// Complete AJAX form submission
$("form").submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize())
.done(function(response) { $("#result").html(response); })
.fail(function() { alert("Submission failed"); });
});Global AJAX Events
Attach handlers that fire for ALL AJAX requests on the page:
$(document)
.ajaxStart(function() {
$("#loader").show(); // Show loading indicator
})
.ajaxStop(function() {
$("#loader").hide(); // Hide loading indicator
})
.ajaxError(function(e, xhr, settings, error) {
console.log("AJAX error on " + settings.url + ": " + error);
})
.ajaxSuccess(function(e, xhr, settings) {
console.log("AJAX success: " + settings.url);
});AJAX Setup
Set defaults for all AJAX requests:
$.ajaxSetup({
timeout: 10000,
headers: {
"X-CSRF-Token": $('meta[name="csrf-token"]').attr("content")
},
error: function(xhr, status) {
if (status === "timeout") {
alert("Request timed out");
}
}
});
// After setup, short forms inherit the defaults
$.get("api/data").done(handleData); // Automatically has CSRF token and 10s timeout
JavaScript vs jQuery: AJAX
| Task | Vanilla JavaScript | jQuery |
|---|---|---|
| GET request | fetch(url).then(r => r.json()) | $.getJSON(url, fn) |
| POST request | fetch(url, {method:"POST", body: data}) | $.post(url, data, fn) |
| Form serialization | new FormData(form) | $(form).serialize() |
| Error handling | .catch() | .fail() |
| Multiple requests | Promise.all([...]) | $.when(...) |
Common Mistakes
1. Not Preventing Default Form Submission
// WRONG — page refreshes, AJAX never fires
$("form").submit(function() {
$.post("api/save", $(this).serialize());
});
// RIGHT
$("form").submit(function(e) {
e.preventDefault();
$.post("api/save", $(this).serialize());
});2. Forgetting Error Handlers
Failed AJAX requests silently fail without error handlers. Users see nothing broken — data just doesn’t appear. Always provide a .fail() handler.
3. Expecting Synchronous Behavior
// WRONG — data is undefined (request hasn't returned)
var data;
$.get("api/data", function(response) { data = response; });
console.log(data); // undefined!
// RIGHT — use data inside the callback
$.get("api/data", function(response) {
console.log(response); // Available here
});4. Not Setting contentType for JSON Requests
// WRONG — sends as form-encoded, server can't parse JSON
$.ajax({
url: "api/save",
method: "POST",
data: JSON.stringify({ name: "Alice" }) // contentType still default!
});
// RIGHT
$.ajax({
url: "api/save",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ name: "Alice" }),
dataType: "json"
});5. Not Encoding Special Characters in Data
When building query strings manually:
// jQuery handles encoding automatically
$.get("api/search", { q: "hello world & co" });
// Manual — must encode!
$.get("api/search?q=" + encodeURIComponent("hello world & co"));Practice Questions
1. What’s the difference between $.get() and $.ajax()?
$.get() is a shorthand for $.ajax({ method: "GET" }). $.ajax() gives full control over all request parameters.
2. What does .load() do that $.get() doesn’t?
.load() automatically injects the response HTML into the matched element and can load page fragments ("page.html #content").
3. How do you handle AJAX errors?
Use .fail() on the promise, or pass an error callback in $.ajax(). Set a global handler with $(document).ajaxError().
4. How do you cancel an AJAX request?
Call .abort() on the XHR object: var xhr = $.ajax(...); xhr.abort();
5. Challenge: Build a live search that queries an API as the user types, with debouncing (300ms delay after the last keystroke) and a loading indicator.
Answer
var searchTimeout;
$("#searchBox").on("input", function() {
clearTimeout(searchTimeout);
var query = $(this).val().trim();
if (query.length < 2) { $("#results").empty(); return; }
$("#loader").show();
searchTimeout = setTimeout(function() {
$.get("api/search", { q: query })
.done(function(data) { renderResults(data); })
.fail(function() { $("#results").html("<p>Search failed</p>"); })
.always(function() { $("#loader").hide(); });
}, 300);
});FAQ
Try It Yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Search Demo</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 40px auto; }
#searchBox { width: 100%; padding: 12px; font-size: 16px; border: 2px solid #ddd; border-radius: 8px; }
#searchBox:focus { border-color: #1a73e8; outline: none; }
#results { margin-top: 16px; }
#results .user { padding: 12px; border-bottom: 1px solid #eee; cursor: pointer; }
#results .user:hover { background: #f5f5f5; }
#results .user h3 { margin: 0; font-size: 16px; }
#results .user p { margin: 4px 0 0; color: #666; font-size: 14px; }
#loader { display: none; text-align: center; padding: 20px; color: #999; }
#status { margin-top: 8px; font-size: 14px; color: #999; }
</style>
</head>
<body>
<h1>Live User Search</h1>
<input type="text" id="searchBox" placeholder="Type to search users...">
<div id="status"></div>
<div id="loader">Searching...</div>
<div id="results"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(function() {
var searchTimeout;
var users = [
{ name: "Alice Johnson", email: "alice@example.com", role: "Admin" },
{ name: "Bob Smith", email: "bob@example.com", role: "Editor" },
{ name: "Charlie Brown", email: "charlie@example.com", role: "Viewer" },
{ name: "Diana Prince", email: "diana@example.com", role: "Admin" },
{ name: "Eve Wilson", email: "eve@example.com", role: "Editor" },
{ name: "Frank Castle", email: "frank@example.com", role: "Viewer" },
{ name: "Grace Hopper", email: "grace@example.com", role: "Admin" },
{ name: "Henry Ford", email: "henry@example.com", role: "Editor" },
];
$("#searchBox").on("input", function() {
clearTimeout(searchTimeout);
var query = $(this).val().trim();
if (query.length < 1) { $("#results").empty(); $("#status").text(""); return; }
$("#loader").show();
searchTimeout = setTimeout(function() {
$.get("api/search", { q: query })
.done(function(data) { renderResults(data); })
.fail(function() {
var filtered = users.filter(function(u) {
return u.name.toLowerCase().includes(query.toLowerCase()) ||
u.email.toLowerCase().includes(query.toLowerCase());
});
renderResults(filtered);
})
.always(function() { $("#loader").hide(); });
}, 300);
});
function renderResults(data) {
var $results = $("#results").empty();
if (data.length === 0) {
$results.html("<p style='color:#999'>No users found</p>");
$("#status").text("0 results");
return;
}
$.each(data, function(i, user) {
$results.append('<div class="user"><h3>' + $("<span>").text(user.name).html() +
'</h3><p>' + $("<span>").text(user.email).html() + ' — ' + user.role + '</p></div>');
});
$("#status").text(data.length + " result" + (data.length !== 1 ? "s" : ""));
}
});
</script>
</body>
</html>What’s Next
| Topic | Description |
|---|---|
| https://tutorials.dodatech.com/frameworks/jquery/jquery-advanced/ | Advanced patterns: promises, plugins, performance |
| https://tutorials.dodatech.com/frameworks/jquery/jquery-ui/ | jQuery UI widgets that use AJAX |
| https://tutorials.dodatech.com/frameworks/jquery/jquery-reference/ | Complete AJAX method reference |
| JSON | JSON data format for API responses |
| REST API | RESTful API design and consumption |
What’s Next
Congratulations on completing this Jquery Ajax tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro