Examples abound of methods to initiate a web (HTTP) request in Javascript. But, when I initiate a web request and the server return a blank response, Firefox at least throws an error:
XML Parsing Error: no root element found Location: http://example.com/service Line Number 1, Column 1: 1 service:1:1
I am using a function similar to:
function RequestGET(url) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.send();
}
In this particular case, the server has nothing to return and I expect that. So, how do I structure my client-side script to handle this response without throwing this error? Or, more generally, how can I handle a non-XML response properly?
For probably a defensible reason, Firefox sets the default MIME type to XML (not sure if it's text/xml
or application/xml
). Thankfully, the XMLHttpRequest
object has an overrideMimeType
method, which I can use to set the MIME type to text/plain
.
The following function works to ignore responses, blank or otherwise:
function RequestGET(url, callback) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
if (req.overrideMimeType)
req.overrideMimeType("text/plain");
req.send(null);
}
responseXML
may === null
The XMLHttpRequest.responseXML property is a read-only value which returns a Document containing the HTML or XML retrieved by the request, or null if the request was unsuccessful, has not yet been sent, or if the retrieved data can't be correctly parsed as XML or HTML.
Something like the below will catch and handle the many possible returns we can expect.
var xhr = new XMLHttpRequest(),
handleResponses = function( x ) {
var s = x.status;
if ( s < 400 ) {
if ( s === 200 ) {
var rXML = x.responseXML;
if ( rXML !== null ) {
console.log( rXML );
} else {
console.error( "Not XML" );
console.log( x.response );
}
} else {
console.warn(
{ 204: "No Content",
304: "Not Modified" // etc.
}[ s ] || "Nothingness..."
);
}
} else {
console.error(
{ 400: "Bad Request",
404: "Not Found" // etc.
}[ s ] || "Oh snap!"
);
}
};
xhr.open( "GET", "https://example.com/service", true );
xhr.addEventListener( "error", function() {
// If this happens, the request effectively failed.
console.error( "The internet is empty" );
}, false );
xhr.addEventListener( "readystatechange", function() {
// Even if the request fails, this will happen.
if ( xhr.readyState === 4 ) {
handleResponses( xhr );
}
}, false );
xhr.send();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With