JSON and AJAX are two pillars of modern web development.
One is the language of data exchange, and the other is the bridge between browser and server.

Think of it like this:

  • JSON → the package containing information 📦
  • AJAX → the delivery system 🚚

Together, they make websites dynamic, fast, and interactive without refreshing the page.


Part 1 — What is JSON?

Definition

JSON stands for:

JavaScript Object Notation

It is a lightweight format used to store and exchange data between:

  • Browser ↔ Server
  • APIs ↔ Applications
  • Frontend ↔ Backend

Even though it comes from JavaScript, JSON is language-independent and supported by almost every programming language.


Why JSON Was Created

Before JSON, XML was widely used.

XML was:

  • Heavy
  • Complex
  • Verbose

Example XML:

<student>
   <name>Anas</name>
   <age>21</age>
</student>

JSON made the same thing simpler:

{
   "name": "Anas",
   "age": 21
}

Cleaner. Faster. Easier.

That simplicity made JSON the king of APIs.


Structure of JSON

JSON stores data as:

  • Objects
  • Arrays
  • Key-value pairs

JSON Object

{
   "name": "Anas",
   "age": 21,
   "isStudent": true
}

Rules of JSON

1. Keys must be inside double quotes

✅ Correct

{
   "name": "Anas"
}

❌ Wrong

{
   name: "Anas"
}

2. Strings use double quotes

✅ Correct

{
   "city": "Mumbai"
}

3. Data is in key-value pairs

{
   "key": "value"
}

4. Values can be:

  • String
  • Number
  • Boolean
  • Array
  • Object
  • null

Example:

{
   "name": "Anas",
   "age": 21,
   "marks": [90, 85, 88],
   "address": {
      "city": "Mumbai"
   },
   "passed": true
}

JSON vs JavaScript Object

This confuses many beginners.

JavaScript Object

let student = {
   name: "Anas",
   age: 21
};

JSON

{
   "name": "Anas",
   "age": 21
}

Main Difference

JavaScript Object JSON
Used inside JS Used for data transfer
Keys may not need quotes Keys must have quotes
Can contain functions Cannot contain functions

Converting JavaScript Object to JSON

Use:

JSON.stringify()

Example

let student = {
    name: "Anas",
    age: 21
};

let jsonData = JSON.stringify(student);

console.log(jsonData);

Output:

{"name":"Anas","age":21}

Why stringify?

Because servers usually understand text, not JavaScript objects.

So:

Object → JSON String → Server

Converting JSON to JavaScript Object

Use:

JSON.parse()

Example

let data = '{"name":"Anas","age":21}';

let obj = JSON.parse(data);

console.log(obj.name);

Output:

Anas

Real-Life Example of JSON

When you log into a website:

{
   "username": "anas123",
   "token": "abc123xyz"
}

When you order food:

{
   "item": "Burger",
   "price": 250,
   "quantity": 2
}

JSON silently powers almost every modern application.


Part 2 — What is AJAX?

Definition

AJAX stands for:

Asynchronous JavaScript And XML

Ironically, today AJAX mostly uses JSON instead of XML.


What AJAX Does

AJAX allows a webpage to:

✅ Send requests to server
✅ Receive data from server
✅ Update webpage
✅ Without refreshing page


Before AJAX

Every action refreshed the page.

Example:

  1. Click submit
  2. Entire page reloads
  3. Wait again

Slow and annoying.


After AJAX

Only required data changes.

Examples:

  • Instagram likes ❤️
  • Live chat 💬
  • Google search suggestions 🔍
  • YouTube comments
  • Gmail inbox updates

All powered by AJAX.


Understanding “Asynchronous”

Synchronous

Tasks happen one by one.

Task 1 → Finish → Task 2

Asynchronous

Tasks can happen in background.

Request sent →
Continue working →
Response comes later

This prevents the webpage from freezing.


AJAX Working Flow

User Action
    ↓
JavaScript Sends Request
    ↓
Server Processes Request
    ↓
Server Sends Response
    ↓
JavaScript Updates Page

Traditional Page vs AJAX

Traditional

Click → Full Reload → New Page

AJAX

Click → Data Fetch → Update Part Only

Ways to Perform AJAX

There are mainly 3 methods:

  1. XMLHttpRequest (Old)
  2. Fetch API (Modern)
  3. Axios (Library)

1. XMLHttpRequest (Old AJAX Method)

Basic Syntax

let xhr = new XMLHttpRequest();

xhr.open("GET", "data.json");

xhr.send();

Complete Example

data.json

{
   "name": "Anas",
   "course": "JavaScript"
}

JavaScript

let xhr = new XMLHttpRequest();

xhr.open("GET", "data.json", true);

xhr.onload = function () {
    
    if (xhr.status === 200) {
        
        let data = JSON.parse(xhr.responseText);

        console.log(data.name);
    }
};

xhr.send();

Logic Breakdown

Step 1

let xhr = new XMLHttpRequest();

Creates AJAX request object.


Step 2

xhr.open("GET", "data.json", true);

Opens connection.

Parameters

Parameter Meaning
GET Request type
data.json File/API
true Asynchronous

Step 3

xhr.onload = function ()

Runs when response arrives.


Step 4

xhr.status === 200

Checks success.

200 = OK


Step 5

JSON.parse()

Converts JSON text into JavaScript object.


Step 6

xhr.send();

Sends request.


2. Fetch API (Modern AJAX)

Today this is preferred.

Cleaner. Easier. Promise-based.


Basic Fetch Syntax

fetch("data.json")
    .then(response => response.json())
    .then(data => console.log(data));

Complete Example

fetch("data.json")
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        console.log(data.name);
        console.log(data.course);
    })
    .catch(function(error) {
        console.log(error);
    });

Logic Flow

Step 1

fetch("data.json")

Sends request.


Step 2

response.json()

Converts response into JavaScript object.


Step 3

.then(data => ...)

Handles successful data.


Step 4

.catch()

Handles errors.


Using Async/Await with Fetch

Modern professional style.


Example

async function getData() {

    try {

        let response = await fetch("data.json");

        let data = await response.json();

        console.log(data);

    } catch(error) {

        console.log(error);
    }
}

getData();

Why async/await is Better

Instead of messy chaining:

.then()
.then()
.then()

It looks synchronous and cleaner.


AJAX Request Types


GET Request

Used to FETCH data.

fetch("users.json")

POST Request

Used to SEND data.

fetch("https://example.com/api", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Anas",
        age: 21
    })
});

Logic of POST Request

headers

Tell server data type.


body

Actual data sent.


JSON.stringify()

Converts object into JSON string.


Real API Example

Using free API:

fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => console.log(data));

This returns user data from server.


Example Output

[
   {
      id: 1,
      name: "Leanne Graham"
   }
]

Display API Data in HTML

HTML

<ul id="users"></ul>

JavaScript

fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => {

        let users = document.getElementById("users");

        data.forEach(function(user) {

            users.innerHTML += `
                <li>${user.name}</li>
            `;
        });
    });

What Happens Internally

Browser requests API
        ↓
Server sends JSON
        ↓
JavaScript converts JSON
        ↓
HTML updates dynamically

That is modern web development in action.


Common HTTP Status Codes

Code Meaning
200 Success
201 Created
400 Bad Request
401 Unauthorized
404 Not Found
500 Server Error

Common AJAX Errors

1. Network Error

No internet/server issue.


2. Invalid JSON

Broken JSON format.


3. CORS Error

Browser blocks request from another domain.


JSON + AJAX Together

This is the real workflow:

Frontend JavaScript
       ↓
AJAX Request
       ↓
Server/API
       ↓
JSON Response
       ↓
JavaScript Updates UI

Real-World Applications

Application Usage
WhatsApp Web Live messages
Instagram Likes/comments
Amazon Product loading
YouTube Video suggestions
Gmail Inbox updates
Google Maps Dynamic map loading

Mini Project Example

Live Weather App

Flow:

User enters city
       ↓
AJAX fetches weather API
       ↓
API returns JSON
       ↓
JavaScript displays temperature

This single flow powers thousands of real applications.


Important Interview Questions

Difference Between JSON and AJAX?

JSON AJAX
Data format Technique
Stores/transfers data Fetches data
Lightweight text Uses JavaScript

Why JSON is Popular?

  • Lightweight
  • Fast
  • Easy to read
  • Language independent

Why AJAX is Important?

  • Faster user experience
  • No page reload
  • Real-time applications
  • Better performance

Best Practices

Always Handle Errors

.catch(error => console.log(error))

Use async/await

Cleaner and professional.


Validate JSON

Never trust external API blindly.


Avoid Blocking UI

Use asynchronous requests properly.


Final Summary

JSON

  • Data format
  • Lightweight
  • Used in APIs
  • Easy data exchange

AJAX

  • Technique for server communication
  • Updates page without reload
  • Uses asynchronous requests
  • Commonly uses JSON

Golden Analogy

Imagine a restaurant:

  • AJAX = waiter carrying requests/responses 🍽️
  • JSON = food package/data 📦
  • Server = kitchen 👨‍🍳
  • Browser = customer table 🪑

The customer does not rebuild the restaurant every time food arrives.
Only the table updates.

That is exactly how modern websites work.

[Mid-Post Ad Placeholder]