jQuery with JSON API
Combining jQuery AJAX with a JSON API lets you fetch live data from external services and build dynamic content. This is how modern web applications display weather, stock prices, social feeds, news headlines, and product listings — all loaded on demand without page refreshes.
What is a JSON API?
A JSON API is a web service that accepts HTTP requests and returns data in JSON format. You send a URL request, the API sends back a structured JSON object, and your jQuery code reads it and builds the HTML.
Diagram: jQuery + JSON API Flow
Your Web Page
│
│ $.getJSON("https://api.example.com/products")
▼
API Server
│
│ Returns:
│ [
│ { "id":1, "name":"Laptop", "price":49999 },
│ { "id":2, "name":"Mouse", "price":799 },
│ { "id":3, "name":"Keyboard","price":1499 }
│ ]
▼
jQuery parses JSON automatically
│
│ $.each(data, function(i, item) { ... })
▼
HTML table/list/cards built dynamically on the page
Using a Free Public API — JSONPlaceholder
JSONPlaceholder (jsonplaceholder.typicode.com) is a free practice API with fake posts, users, and todos.
$(document).ready(function() {
$.getJSON("https://jsonplaceholder.typicode.com/posts?_limit=5", function(posts) {
$.each(posts, function(i, post) {
var html = "<div class='post-card'>" +
"<h3>" + post.title + "</h3>" +
"<p>" + post.body + "</p>" +
"<small>Post ID: " + post.id + "</small>" +
"</div>";
$("#postList").append(html);
});
});
});
Fetching Users and Displaying in a Table
$(document).ready(function() {
$.getJSON("https://jsonplaceholder.typicode.com/users", function(users) {
$.each(users, function(i, user) {
var row = "<tr>" +
"<td>" + user.id + "</td>" +
"<td>" + user.name + "</td>" +
"<td>" + user.email + "</td>" +
"<td>" + user.address.city + "</td>" +
"</tr>";
$("#userTable tbody").append(row);
});
});
});
Accessing Nested JSON Properties
// JSON response:
{
"id": 1,
"name": "Leanne Graham",
"email": "leanne@april.biz",
"address": {
"street": "Kulas Light",
"city": "Gwenborough",
"zipcode": "92998-3874"
},
"company": {
"name": "Romaguera-Crona"
}
}
// Access nested values:
user.name → "Leanne Graham"
user.address.city → "Gwenborough"
user.company.name → "Romaguera-Crona"
Search/Filter API Results
$(document).ready(function() {
var allUsers = [];
// Fetch all users once
$.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {
allUsers = data;
renderUsers(allUsers);
});
// Filter on search input
$("#search").on("input", function() {
var query = $(this).val().toLowerCase();
var filtered = $.grep(allUsers, function(user) {
return user.name.toLowerCase().indexOf(query) !== -1 ||
user.email.toLowerCase().indexOf(query) !== -1;
});
renderUsers(filtered);
});
function renderUsers(users) {
$("#userList").empty();
if (users.length === 0) {
$("#userList").text("No users found.");
return;
}
$.each(users, function(i, user) {
$("#userList").append(
"<li><strong>" + user.name + "</strong> — " + user.email + "</li>"
);
});
}
});
Diagram: Search Filter Flow
All 10 users loaded on page load
│
User types "le" in search box
│
$.grep filters allUsers:
"Leanne Graham" → contains "le" → kept
"Ervin Howell" → contains "le" (ervin) → no
"Clementine..." → contains "le" → kept
│
renderUsers([Leanne, Clementine, ...])
│
Only matching users shown instantly (no new API call)
Sending Data to a JSON API with POST
$(document).ready(function() {
$("#postForm").submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "POST",
contentType: "application/json",
data: JSON.stringify({
title: $("#title").val(),
body: $("#body").val(),
userId: 1
}),
dataType: "json",
success: function(response) {
$("#result").text("Created post with ID: " + response.id);
},
error: function() {
$("#result").text("Failed to create post.");
}
});
});
});
Handling API Errors Gracefully
$.getJSON("https://api.example.com/data")
.done(function(data) {
renderData(data);
})
.fail(function(xhr, status, error) {
var msg = "";
if (xhr.status === 401) {
msg = "Unauthorised. Please log in.";
} else if (xhr.status === 404) {
msg = "Data not found.";
} else if (xhr.status === 429) {
msg = "Too many requests. Please wait and try again.";
} else {
msg = "Could not load data (" + error + ").";
}
$("#errorBox").text(msg).show();
});
Quick Summary
- Use
$.getJSON(url, callback)to fetch and auto-parse JSON from an API. - Access nested JSON properties with dot notation:
user.address.city. - Use
$.each()to loop over JSON arrays and build HTML dynamically. - Store fetched data in a variable to enable client-side filtering without repeat API calls.
- Use
$.ajax()withcontentType: "application/json"andJSON.stringify()to POST JSON data. - Always handle API errors with
.fail()and show user-friendly messages.
