'XHR/AJAX Won't Handle 404 Error - XHR Stops Working
I'm having a surprisingly difficult time handling a simple 404 error response with XHR (AJAX)...
Basically, I have an "infinite scroll" page, where users scroll down the page and AJAX loads the next 50 results. At some point it will run out of results, and my PHP script is purposely set up to return a header 404 status when there are no more results. This is what I have:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if(this.status == 200) {
console.log('display next results list');
}
else if(this.status == 404) {
console.log('end of list');
}
}
}
xhttp.open("GET", "index.php?page=101", true);
xhttp.send();
Problem: When a 404 is returned, I'm seeing the red "GET" 404 error in Chrome's dev console. When I click the error in console to see where it happens in the source, it specifically happens on this line xhttp.send(); The worst part about it is this seems to kill off XHR. So if I scroll back up again to see previous pages, XHR no longer works after it receives a 404. XHR just dies...
How do I fix this? How do I get XHR to see the 404 response and simply follow the else if(this.status == 404) { function without completely crashing???
Thanks
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
