AJAX – Server Response

In the context of AJAX (Asynchronous JavaScript and XML), handling the server’s response is a critical aspect of creating dynamic, interactive web applications. After sending a request via the XMLHttpRequest object, the server processes the request and sends back a response, which your JavaScript code can use to update the web page dynamically.

Steps to Handle Server Responses

  1. Initiate a Request: Use the XMLHttpRequest object to send a request to the server.
  2. Wait for Response: Monitor the readyState property and ensure the value is 4 (DONE) before processing the response.
  3. Check Status Code: Use the status property to verify the HTTP status code (e.g., 200 for success).
  4. Process the Data: Parse and use the server’s response (responseText, responseXML, or other formats).

Common Server Response Formats

  • Plain Text:
    • The simplest form, sent as a string.
    • Accessed using xhr.responseText.
  • JSON (JavaScript Object Notation):
    • A structured format ideal for transmitting data between a server and a web application.Easily parsed into JavaScript objects using JSON.parse().
    Example:
let data = JSON.parse(xhr.responseText);
  • XML:
    • An older format, parsed using responseXML.
    • Useful for applications that rely heavily on XML for data structures.
  • HTML:
    • Full or partial HTML that can be inserted directly into the DOM.

Example: Handling a JSON Server Response

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);

xhr.onload = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    let data = JSON.parse(xhr.responseText);
    console.log("Server response:", data);
    document.getElementById("output").textContent = data.message;
  } else {
    console.error("Error:", xhr.status, xhr.statusText);
  }
};

xhr.onerror = function() {
  console.error("Network error occurred.");
};

xhr.send();

XMLHttpRequest Properties for Responses

  • responseText:
    • Contains the raw text of the server’s response.
    • Example:
console.log(xhr.responseText);
  • responseXML:
    • Parses the response into an XML document.
    • Example:
let xmlDoc = xhr.responseXML;
console.log(xmlDoc.getElementsByTagName("title")[0].textContent);
  • status and statusText:
    • HTTP status code and description.
    • Common status codes:
      • 200 OK: Request successful.
      • 404 Not Found: Resource not found.
      • 500 Internal Server Error: Server-side issue.

Updating the Web Page Dynamically

AJAX enables dynamic content updates without reloading the page. Here’s an example of inserting the server’s response into the DOM:

xhr.onload = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    document.getElementById("output").innerHTML = xhr.responseText;
  }
};

Handling Errors in Server Responses

Robust error handling ensures a better user experience:

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

xhr.onerror = function() {
  console.error("Network error.");
};

Example: Real-Time Search with AJAX

Dynamic applications like real-time search rely on server responses to provide immediate results:

function searchQuery(query) {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", `/search?q=${encodeURIComponent(query)}`, true);

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

  xhr.send();
}

Conclusion

Handling server responses in AJAX applications enables seamless user experiences by dynamically updating content without page reloads. Understanding the different formats and response properties allows developers to build robust, interactive applications. For more JavaScript and AJAX tutorials, visit The Coding College.

Leave a Comment