← Back to Chapters

jQuery AJAX with JSON

? jQuery AJAX with JSON

? Quick Overview

jQuery AJAX with JSON allows web pages to communicate with servers asynchronously and exchange data in JSON format without reloading the page.

? Key Concepts

  • AJAX stands for Asynchronous JavaScript and XML
  • JSON is a lightweight data interchange format
  • jQuery simplifies AJAX requests using built-in methods

? Syntax / Theory

The $.ajax() and $.getJSON() methods are commonly used to fetch JSON data from servers.

? Code Example

? View Code Example
// Fetch JSON data using jQuery AJAX
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
method: "GET",
dataType: "json",
success: function(data) {
console.log(data);
}
});

? Live Output / Explanation

Explanation

The AJAX call fetches user data in JSON format and logs it to the browser console without refreshing the page.

? Interactive Example

Click the button above to fetch data...
? View Code Example
// Load JSON data and display it dynamically
$("#loadData").click(function() {
$.getJSON("https://jsonplaceholder.typicode.com/users", function(users) {
let html = "<ul>";
users.forEach(function(user) {
html += "<li>" + user.name + "</li>";
});
html += "</ul>";
$("#result").html(html);
});
});

? Use Cases

  • Loading data dynamically
  • Form submissions without page reload
  • Fetching API data

✅ Tips & Best Practices

  • Always handle error callbacks
  • Use proper data types
  • Validate JSON responses

? Try It Yourself

  • Fetch posts instead of users
  • Display data in a table
  • Add error handling