XHR/AJAX Won't Handle 404 Error - XHR Stops Working - ajax

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

Related

Taking value from text-field and sending it with AJAX request Javascript

I am trying to sync both client-side and server-side scripts that the client intakes a value from the textbox and sends it to the server, upon which the server displays that input as a cookie.
Here is the code that I have so far
function loadCookie() {
//[1] make a new request object
var xhttp = new XMLHttpRequest();
//[2] set the request options
xhttp.open("GET", "index.html", true);
//[3] define what you will do when you ge a response (callback)
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input_response").innerHTML = this.responseText;
}
};
//[4] finally send out the request
xhttp.send();
}
I have the and the button but I am having issue of the page re-loading itself instead of taking the value of the input and showing it as a cookie in the server. I'm suspecting it is having to do with the URL by the index.html

When is a HTTP response code actually 200 OK?

In creating an API (and other things), many client-side examples look like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
...
So that got me thinking, what is actually OK?
Specifically, if the request produces a programmed error for something like bad data, the request has technically worked so is this "OK"? And then, what should the severity of the error be to return a 400 - bad login?

jsp ajax call throwing 500 (Internal Server Error)

I am attempting ajax call on change of a value in .jsp which is as follows:-
$(".custodianautocomplete").change(function() {
$('#custodianIDSelected').html($(this).val());
var IDSelected = $(this).val();
if (window.XMLHttpRequest) {
xRequest1 = new XMLHttpRequest();
} else {
xRequest1 = new ActiveXObject("Microsoft.XMLHTTP");
}
xRequest1.onreadystatechange = function() {
if ((xRequest1.readyState == 4) && (xRequest1.status == 200)) {
$(this).parent("td").next().find("input[name=hall_location]").val(xRequest1.responseText);
}
}
xRequest1.open("get", "/chbs/adm/getEmpName.jsp?q=" + IDSelected, "true");
xRequest1.send();
});
The execution of the webpage does not even reach getEmpName.jsp and an error as follows is shown in console
updateHallNames.jsp:254 GET http://localhost:8080/chbs/adm/getEmpName.jsp?q=ISRO008 500 (Internal Server Error)
(anonymous) # updateHallNames.jsp:254
dispatch # jquery-3.2.1.min.js:1627
q.handle # jquery-3.2.1.min.js:1589
The line No 254 shown in updateHallNames.jsp:254 is pointing at xRequest1.send();
I am unable to figure out the reason for the error.
I have resolved the error. The problem was with the error in the code of getEmpName.jsp. I found the details of the error by using standard ajax functionality with .fail(). The amended code is available at the link
here

Express.js res.render not redirecting, just displayed in console

This time I want to use res.render to display html as success of DB update. I did it several times, but this time it doesn't work. It's not render html file, just displayed on chrome's console.
I think it caused because of async problem or duplicated response. I tried to many ways but I couldn't solve it, so pointers appreciated.
The code is related when the user paid service, increase user's level.
Get Access Token => Validate => res.render
app.post('/payment/validate', function(req, res, next){
// Get access token
request.post({
url : 'https://payment-company/get/token'
}, function(err, response, body) {
if(!err & response.statusCode == 200) {
var result = JSON.parse(body);
var accessToken = result.response.access_token;
// Validate payment (compare paid and would be paid)
request.get({
headers : { 'Authorization' : accessToken }
url : 'https://payment-company/find/paymentid'
}, function (err, response, body) {
if (!err && response.statusCode == 200){
var result = JSON.parse(body);
if (result.response.amount == req.body.price){
Members.findOne({id : req.user.id}, function(err, member){
// If no problem, update user level
member.level = 2;
member.save(function(err, result){
if (err) return next();
res.render('payment.view.result.ejs',
{
title : 'Success !',
description : 'level up.'
});
});
});
}
} else {
...
}
});
}
})
});
sorry to verbose code I tried to shorten code, No problem until res.render, res.render will work but it's not display page instead it just send html code to chrome's console.
Looks like there's a bit of a misunderstanding of how these requests work. What I think you intend:
Browser makes a GET request, server responds with an HTML document, the browser renders it
User takes an action
Browser makes a POST request, server responds with an HTML document, the browser renders it
What you've started coded on the frontend is an alternate method:
You make a POST request via AJAX, server responds with some JSON, you modify the current document with JavaScript to let the user know

NS_Binding_Aborted error for ajax function

I have a link on click of which a request should go to web server and on successful execution a redirection should happen. I have used ajax for this but I am getting NS_Binding_Aborted error in HTTpFox.
The code:
<a id="lnkredirect" href="javascript:void(0);" onclick="myfunction();">Some text</a>
The ajax code:
function myfunction(){
$.ajax({
url: Web server Url,
type: 'POST',
datatype: 'JSON',
timeout: 20000,
data: null,
success: function{ $("#lnkredirect").attr('href','redirection link...');},
error : function{ $("#lnkredirect").attr('href','redirection link...');}
)};
return true;
}
The redirection is happening but I am getting NS_Binding_Aborted error in Firefox. In both success and error scenario, the redirection should happen but why NS_Binding_Aborted is coming, I am not sure of this. NS_Binding_Aborted error should come only if one event is cancelling some prior running event but I have already suppressed href of the link and redirecting it once the ajax request is executed, so there should be only one server call and NS_Binding_Aborted should not come. Please let me know where am I going wrong?
I got a similar trouble, also while using both a href and a XmlHttpRequest inside a onclick. My XMLHttpRequest was aborted (ns_binding_aborted) and thus never reached status 200. I also could see that my XHR was "blocked by devtools" in Firefox console.
This was because the page was reloaded (by the href) before it could finish its job (what was in the onclick).
I had something like this:
<script type="text/javascript">
function incrementNumberOfDownloads() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // 4 = request ended, 200 = success
//update displayed number of downloads
document.getElementById("numberOfDownloads").innerHTML = this.responseText;
}
};
xhttp.open("GET", "incrementNumberOfDownloads.php", true);
xhttp.send();
return true;
}
</script>
<p id="numberOfDownloads">42</p>
Download my file !
I fixed the problem by adding a target="_blank" to my download link, so that the page is no more reloaded when clicking, enabling the XMLHttpRequest to finish with success.
This is caused by another request that abort your request. Generally when your goal is reload data o all page just end request and don'ts is synchronized request, a little novell error.
In this case the "return " sentence is the problem, the return sentence must be in success seccion.
My issue fixed, when I've changed calling native js form submit event to jQuery submit event.
// this code
form[0].dispatchEvent(new Event("submit"));
// changed to
form.submit();

Resources