When you dispatch a request to a server, the server eventually returns a response.
The XMLHttpRequest object gives you multiple properties to accurately capture and parse this response.
The responseText property returns the server response as a simple JavaScript string.
This is the most widely used property, as it perfectly captures JSON text, HTML code, or plain text strings.
Once retrieved, you can simply inject this string directly into your HTML DOM using innerHTML!
Before assuming the data is valid, you should always check the HTTP status code.
If this.status == 200, it means the server replied with "OK" and the data is completely valid.
If this.status == 404, it means the server could not find the file you requested!
const xhttp = new XMLHttpRequest();xhttp.onload = function() { // Always check the status before using the data! if (this.status === 200) { document.getElementById("output").innerHTML = this.responseText; } else { document.getElementById("output").innerHTML = "Error: File not found."; } }
xhttp.open("GET", "my_data.txt"); xhttp.send();
Gracefully handling HTTP errors prevents your application from crashing unexpectedly.
If an API endpoint goes down, your users should see a friendly error message, not a broken, unresponsive screen.
Properly managed error states are crucial for building high-quality, professional web applications.
Which HTTP status code signifies that the server request was completely successful ("OK")?