JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

AJAX – Server Response

15 April 2025 | Category:

What is a Server Response?

When you send a request to a server using AJAX, the server processes it and sends a response back to your JavaScript code.

The server response contains:

  • ✅ A status code (e.g., 200 for success)
  • 📦 Data (usually in JSON, XML, or plain text format)

You can then use JavaScript to display or process this data without reloading the webpage.


🔄 How to Handle a Server Response in AJAX?

When using XMLHttpRequest, you handle the response using the onload or onreadystatechange event.


🚀 Example – Display Server Response Using AJAX

<button onclick="getData()">Get Data</button>
<p id="output"></p>

<script>
function getData() {
  const xhr = new XMLHttpRequest();
  xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);

  xhr.onload = function () {
    if (xhr.status === 200) {
      const response = JSON.parse(xhr.responseText); // Convert JSON string to object
      document.getElementById("output").innerText = `Title: ${response.title}`;
    } else {
      document.getElementById("output").innerText = "Error loading data.";
    }
  };

  xhr.send();
}
</script>

Output: Displays the title from the JSON response without reloading the page.


📑 Important XHR Response Properties

PropertyDescription
xhr.responseTextRaw response as a string (JSON, text, etc.)
xhr.responseXMLIf response is XML, you can parse it using this
xhr.statusHTTP status code (e.g., 200 OK, 404 Not Found)
xhr.readyStateTracks the state of the request (0 to 4)

⚠️ Handling Errors

Always check for errors in your response:

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log("Success:", xhr.responseText);
  } else {
    console.error("Error:", xhr.status);
  }
};

✅ Common HTTP Status Codes

CodeMeaning
200OK (Success) ✅
201Created
400Bad Request ❌
404Not Found ❌
500Server Error ❌

🧠 Note: Response Format Matters

  • Most modern APIs return JSON.
  • Always parse JSON using JSON.parse() if you’re using responseText.
const jsonData = JSON.parse(xhr.responseText);

🔚 Summary

  • AJAX lets you get server responses without reloading the page.
  • Use xhr.responseText to access the data.
  • Always check xhr.status to handle errors properly.
  • Convert JSON responses using JSON.parse().