πŸ’» JSON in Web Development (AJAX & APIs)
Estimated reading: 3 minutes 36 views

πŸ”„ Sending and Receiving JSON with AJAX – A Complete Guide (2025)


🧲 Introduction – JSON & AJAX in Modern Web Apps

AJAX (Asynchronous JavaScript and XML) allows web pages to send and receive data without reloading. While the term includes “XML”, in modern web development, JSON is the preferred data format due to its lightweight structure and ease of use with JavaScript.

Using AJAX with JSON, you can communicate with servers, submit forms, fetch dynamic content, or even build single-page applicationsβ€”all without refreshing the page.

🎯 In this guide, you’ll learn:

  • How to send JSON data using AJAX
  • How to receive and handle JSON responses
  • Syntax for XMLHttpRequest and fetch()
  • Real-world usage examples

πŸ“¦ Why Use JSON with AJAX?

BenefitDescription
LightweightSmaller payloads than XML
Native JS supportEasy parsing using JSON.parse()
Human-readableClean and developer-friendly
UniversalSupported across all browsers and languages

βœ… Using XMLHttpRequest to Send JSON

πŸ§ͺ Example – Sending JSON Data via POST

const xhr = new XMLHttpRequest();
const data = JSON.stringify({
  username: "alice",
  password: "secure123"
});

xhr.open("POST", "https://example.com/api/login", true);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const response = JSON.parse(xhr.responseText);
    console.log("Login Success:", response);
  }
};

xhr.send(data);

πŸ” Explanation:

  • open("POST", URL) sets up the request
  • setRequestHeader() tells the server we’re sending JSON
  • send(data) sends the stringified JSON
  • xhr.responseText is parsed into a usable object

βš™οΈ Receiving JSON Data via XMLHttpRequest

πŸ§ͺ Example – GET Request

const xhr = new XMLHttpRequest();

xhr.open("GET", "https://api.example.com/users", true);

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const users = JSON.parse(xhr.responseText);
    console.log("Received Users:", users);
  }
};

xhr.send();

πŸš€ Using fetch() API – Modern Approach

πŸ§ͺ Example – Sending JSON with fetch()

fetch("https://example.com/api/register", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Bob",
    email: "bob@example.com"
  })
})
  .then(response => response.json())
  .then(data => {
    console.log("Registration successful:", data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

βœ… Benefits of fetch():

  • Promise-based
  • Cleaner and more readable than XMLHttpRequest
  • Easily used with async/await

πŸ” Receiving JSON with fetch()

fetch("https://api.example.com/products")
  .then(res => res.json())
  .then(data => {
    console.log("Product List:", data);
  });

πŸ›‘οΈ Best Practices for JSON + AJAX

Best PracticeWhy It Matters
Use proper headersAlways set Content-Type: application/json
Validate JSON on the serverPrevents malformed data
Handle error responses gracefullyAvoids app crashes and improves UX
Use async/await for cleaner codeImproves readability and maintainability

πŸ“Œ Summary – Recap & Next Steps

Using JSON with AJAX is a core skill in modern web development. It allows for smooth, asynchronous communication between client and server without full-page reloads.

πŸ” Key Takeaways:

  • JSON is now the standard format used with AJAX
  • Use XMLHttpRequest or modern fetch() to send/receive data
  • JSON must be stringified before sending and parsed upon receiving
  • AJAX enables dynamic, fast user experiences

βš™οΈ Real-world use:

Used in login systems, e-commerce carts, chat applications, search filters, and dashboard data loading.


❓ FAQ – Sending and Receiving JSON with AJAX


❓ What is the Content-Type header for JSON in AJAX?
βœ… Use Content-Type: application/json to tell the server you’re sending JSON.


❓ Should I use fetch() or XMLHttpRequest?
βœ… Prefer fetch() for modern apps. It’s cleaner and supports promises natively.


❓ Do I need to stringify JSON before sending?
βœ… Yes. Use JSON.stringify(data) before sending in the request body.


❓ How do I parse the JSON response?
βœ… Use response.json() with fetch() or JSON.parse(xhr.responseText) with XMLHttpRequest.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Sending and receiving JSON with AJAX

Or Copy Link

CONTENTS
Scroll to Top