jQuery AJAX and JSON: Dynamic Data Loading & Interaction
What is AJAX?
-
AJAX = Asynchronous JavaScript and XML.
-
Lets you communicate with a server without reloading the whole webpage.
-
Fetch or send data dynamically and update the page content smoothly.
What is JSON?
-
JSON (JavaScript Object Notation) is a lightweight data format.
-
Used to exchange data between client and server.
-
Easy to read/write by humans and machines.
jQuery AJAX Basics
jQuery provides convenient methods to send HTTP requests:
Common AJAX Methods
| Method | Description | Example |
|---|---|---|
$.ajax() |
Full configurable AJAX request | Most flexible method |
$.get() |
Sends a GET request | Simplified GET request |
$.post() |
Sends a POST request | Simplified POST request |
$.getJSON() |
Sends GET request expecting JSON response | Automatically parses JSON |
Simple AJAX GET Example
Fetch JSON data from a server and display it:
Using $.ajax() for More Control
Important AJAX Options
-
url: URL to request. -
methodortype: GET, POST, PUT, DELETE, etc. -
data: Data to send to server (object or string). -
dataType: Expected response format (e.g., ‘json’, ‘xml’, ‘text’). -
success: Callback on success. -
error: Callback on error.
Handling JSON Data
-
jQuery automatically parses JSON responses if
dataType: 'json'or when using$.getJSON(). -
You can easily convert JS objects to JSON strings using
JSON.stringify(). -
Parse JSON strings using
JSON.parse()if needed.
Summary
-
AJAX lets you load and send data without reloading the page.
-
JSON is the most common format for exchanging data.
-
jQuery simplifies AJAX requests with easy methods and automatic JSON handling.
