AJAX – Server Response

Welcome to The Coding College, where we guide you through the fundamentals of modern web development. In this tutorial, we’ll cover how to handle server responses using AJAX. A strong understanding of server responses is crucial for building dynamic and interactive web applications.

What is a Server Response?

When you send a request to a server using AJAX, the server processes the request and sends back a response. The response may include data, success/failure status, or error messages. You use JavaScript to handle and process this response dynamically.

How to Handle Server Responses in AJAX

When working with the XMLHttpRequest object, you interact with the server response using the following steps:

  1. Send a Request: Use the send() method to make the request.
  2. Monitor the Response: Use the onreadystatechange event handler.
  3. Check Response Status: Ensure the request was successful.
  4. Process the Response: Extract and use the data (e.g., JSON, XML, or plain text).

XMLHttpRequest Response Properties

1. readyState

Tracks the progress of the request:

ValueStateDescription
0UNSENTRequest not initialized.
1OPENEDServer connection established.
2HEADERS_RECEIVEDRequest received by the server.
3LOADINGResponse is being received.
4DONERequest is complete, response is ready.

2. status

The HTTP status code of the response:

  • 200: OK (Request succeeded).
  • 404: Not Found (Resource unavailable).
  • 500: Internal Server Error.

3. responseText

The response data as plain text.

4. responseXML

The response data as an XML document (useful for XML-based responses).

Example: Handling a GET Request Response

Let’s fetch data from a server and display it dynamically on a web page.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Server Response</title>
</head>
<body>
    <h1>AJAX Example: Handle Server Response</h1>
    <button id="fetchData">Fetch Data</button>
    <div id="output"></div>
    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

document.getElementById("fetchData").addEventListener("click", function () {
    const xhr = new XMLHttpRequest();

    // Configure the request
    xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);

    // Monitor the response
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText); // Parse JSON response
                document.getElementById("output").innerHTML = `
                    <h2>${response.title}</h2>
                    <p>${response.body}</p>
                `;
            } else {
                console.error("Error:", xhr.status, xhr.statusText);
            }
        }
    };

    // Send the request
    xhr.send();
});

Output:

When you click the “Fetch Data” button, data from the server is displayed dynamically:

Sample Output:

<h2>Sample Post Title</h2>
<p>This is the content of the post.</p>

Example: Handling a POST Request Response

Let’s send data to the server and display the server’s response.

JavaScript:

document.getElementById("fetchData").addEventListener("click", function () {
    const xhr = new XMLHttpRequest();

    // Configure the request
    xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
    xhr.setRequestHeader("Content-Type", "application/json");

    // Monitor the response
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 201) {
                const response = JSON.parse(xhr.responseText); // Parse JSON response
                console.log("Server Response:", response);
            } else {
                console.error("Error:", xhr.status, xhr.statusText);
            }
        }
    };

    // Send the request with data
    const data = JSON.stringify({
        title: "New Post",
        body: "This is a test post sent using AJAX.",
        userId: 1,
    });
    xhr.send(data);
});

Explanation:

  1. The open() method initializes a POST request.
  2. The setRequestHeader() sets the Content-Type to application/json.
  3. The server sends a response indicating success, which is logged to the console.

Response Formats

1. Plain Text (responseText)

If the server sends plain text:

console.log(xhr.responseText); // Output: Hello, World!

2. JSON

JSON is the most common format for server responses in modern web applications. Use JSON.parse() to convert the JSON string into a JavaScript object:

const jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);

3. XML (responseXML)

If the server sends XML:

const xmlResponse = xhr.responseXML;
const title = xmlResponse.getElementsByTagName("title")[0].childNodes[0].nodeValue;
console.log(title);

Handling Errors

It’s essential to handle errors gracefully to improve the user experience.

Example:

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

Best Practices

  1. Check readyState and status: Always ensure the request has completed successfully.
  2. Use Try-Catch Blocks: Wrap response handling in a try block to catch parsing errors.
  3. Optimize Error Messages: Provide clear and user-friendly error messages.
  4. Validate Response Format: Ensure the server sends data in the expected format (e.g., JSON or XML).

Modern Alternatives: Fetch API

Handling server responses is simpler with the Fetch API, which uses Promises for cleaner syntax.

Example:

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then((response) => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then((data) => console.log(data))
    .catch((error) => console.error("Error:", error));

Conclusion

AJAX server responses are a powerful tool for building dynamic web applications. By understanding how to monitor and process responses, you can provide a seamless user experience while maintaining robust server communication.

Leave a Comment