JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Ajax Response


In AJAX, the response is the data returned by the server after a request. Handling the response correctly is key to making web pages dynamic and interactive.

AJAX allows JavaScript to receive this data without reloading the page, which creates smoother user experiences. Responses can be text, HTML, JSON, or XML, depending on the server and application needs.

What Is an AJAX Response?

An AJAX response is the data sent from the server back to the client after a request is made.

When using XMLHttpRequest, the response is accessed through:

  • responseText – Returns the response as plain text.

  • responseXML – Returns the response as an XML document.

  • status – Returns the HTTP status code (e.g., 200 for success).

Handling Response with XMLHttpRequest

Here’s the general way to handle responses using XMLHttpRequest:

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) { // Request is complete
    if (xhr.status === 200) { // Successful response
      console.log("Server Response:", xhr.responseText);
    } else {
      console.error("Error:", xhr.status);
    }
  }
};

xhr.send();

Explanation:

  • readyState === 4 ensures the request is complete.

  • status === 200 confirms a successful server response.

  • xhr.responseText contains the data sent by the server.

Handling JSON Responses

Modern web applications often use JSON for responses because it is easy to read and parse.

Example: JSON Response

user.json

{
  "name": "Vicky",
  "age": 28,
  "email": "vicky@example.com"
}

JavaScript to handle it:

let xhr = new XMLHttpRequest();
xhr.open("GET", "user.json", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    let user = JSON.parse(xhr.responseText); // Convert JSON string to JS object
    document.getElementById("output").innerHTML =
      `Name: ${user.name}<br>Age: ${user.age}<br>Email: ${user.email}`;
  }
};

xhr.send();

Explanation:

  • JSON.parse() converts JSON into a usable JavaScript object.

  • Data is displayed dynamically in a <div> with id "output".

Handling HTML Responses

AJAX responses can also be HTML snippets that can be inserted directly into a page.

let xhr = new XMLHttpRequest();
xhr.open("GET", "snippet.html", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    document.getElementById("container").innerHTML = xhr.responseText;
  }
};

xhr.send();

Explanation:

  • xhr.responseText contains the HTML snippet.

  • innerHTML inserts the content without refreshing the page.

This method is commonly used for dynamic content loading, like tabs or partial page updates.

Handling XML Responses

If the server sends XML data, it can be accessed using responseXML.

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    let xml = xhr.responseXML;
    let items = xml.getElementsByTagName("item");
    for (let i = 0; i < items.length; i++) {
      console.log(items[i].textContent);
    }
  }
};

xhr.send();

Explanation:

  • xhr.responseXML returns a parsed XML document.

  • You can traverse XML nodes using standard DOM methods like getElementsByTagName().

Handling Errors and Status Codes

Always check the status code to ensure the response is valid. Common HTTP status codes include:

Status Meaning
200 OK – successful request
404 Not Found – file or endpoint missing
500 Server Error – internal server issue
403 Forbidden – no permission

Example:

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      console.log("Success:", xhr.responseText);
    } else if (xhr.status === 404) {
      alert("File not found.");
    } else {
      alert("Server error: " + xhr.status);
    }
  }
};

Using the onload Event

onload is an alternative to onreadystatechange for simpler AJAX requests. It runs when the request completes successfully.

let xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    document.getElementById("output").textContent = xhr.responseText;
  } else {
    console.error("Error:", xhr.status);
  }
};

xhr.send();

Advantages:

  • Easier to use than onreadystatechange.

  • Only triggers when the request finishes, so no need to check readyState.

Displaying Response Dynamically in the Page

AJAX responses can be used to update sections of a webpage dynamically.

<button id="loadBtn">Load Response</button>
<div id="output"></div>

<script>
document.getElementById("loadBtn").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "data.txt", true);

  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("output").innerHTML = xhr.responseText;
    } else {
      document.getElementById("output").textContent = "Failed to load data";
    }
  };

  xhr.send();
});
</script>

Explanation:

  • Clicking the button sends the request.

  • The response updates only the <div>.

  • No page reload is required.

Summary of the Tutorial

An AJAX response is the data sent back from the server after a request. Properly handling it allows developers to create dynamic and interactive web applications.

Key points:

  • Responses can be text, HTML, JSON, or XML.

  • Always check the HTTP status code to confirm success.

  • Use onload or onreadystatechange to handle responses.

  • Parse JSON responses using JSON.parse().

  • Insert HTML responses into the DOM to update parts of the page.

Understanding AJAX responses is essential for building modern web apps, real-time dashboards, and dynamic content updates.


Practice Questions

  1. Write an AJAX request to fetch data.txt and display its content inside a <div> when a button is clicked.

  2. Fetch a JSON file (user.json) and display the name and email values in separate <p> elements.

  3. Write code to handle HTML responses by fetching snippet.html and inserting it into a <section> without reloading the page.

  4. Fetch an XML file (data.xml) and log all <item> values in the console.

  5. Create an AJAX request that shows a “Loading…” message while waiting for the server response and replaces it with the actual data once received.

  6. Write code to handle different HTTP status codes (200, 404, 500) and display appropriate messages in a <div>.

  7. Use onload to handle a server response from info.txt and display it in a <p> element.

  8. Parse a JSON array from users.json and create a dynamic list of user names in the DOM.

  9. Create a button that fetches an HTML snippet and appends it to an existing <div> every time the button is clicked.

  10. Write an AJAX request that fetches data from data.txt and logs an error message in the console if the request fails.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top