clearInterval not working with XMLHttpRequest - javascript

I'm trying to get the result, next time of the game in database. I used XMLHttpRequest with 5s delay of setInterval to fetch data. If the status of the request is 200. The code works well. However, if the status is not 200. The clearInterval will not work but console.log still works.
var _resInterval;
_resInterval = setInterval(function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
var _resp = JSON.parse(xhr.responseText);
console.log(_resp);
if (parseInt(_resp.interval) >= 0) {
clearInterval(_resInterval);
restartGame(parseInt(_resp.interval));
}
} else {
console.log("error");
clearInterval(_resInterval);
}
};
xhr.send();
}, 5000);
UPDATE: recursive function
function getGameResult() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/index.php/forms/getDDResult/" + id, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
var _resp = JSON.parse(xhr.responseText);
console.log(_resp);
if (parseInt(_resp.interval) >= 0 && _resp.result != "Not available") {
restartGame(parseInt(_resp.interval));
} else {
setTimeout(function() {
getGameResult();
}, 5000);
}
}
};
xhr.send();
}
Am I doing it the right way or should I change it to recursive function? Thanks.
-- Lara

The problem is that there's a possibility where the clearInterval is called and an XHR is pending a response. When the browser receives the response, the timer is long gone, but still has to handle the response.
If you want your periodic XHR to wait for the response of the previous before launching another, the recursive setTimeout is a better option.

Related

Execute a http request response in javascript

I have an http request which delivers 'JSON.stringify(data)'.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/api/hello", true);
xhr.send();
xhr.onreadystatechange = function () {
console.log(xhr.responseText);
};
How can I run the code and print the contents of data?
your code should be working, the endpoint may be the problem, check the url your trying to get into the endpoint from, then don't forget to check the readyState and the status of your request before doing nothing.
xhr.onreadystatechange = function () {
if (xhr.readState === 4 && xhr.status === 200)
{
console.log(xhr.responseText);
}
};

How to load a json file with javascript locally without Jquery?

I'm creating a website to progress in javascript and I have a little problem, every ways I try, my browser doesn't want to load my json file.
I tried many codes i found on internet but none of them work (or I don't know how to make them work). Finally i fond this one which is quite easy to understand but yhis one too doesn't work and always return an error message.
function loadJSON(path,success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 1) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path , true);
xhr.send();
}
function test()
{
loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}
I run the test function but everytimes, the console return me an error. Someone have an idea to solve my problem ?
status is the HTTP response code.
200 means the request has been successful. The status will most likely never be 1.
Here is a list of HTTP codes
As a solution, I suggest using the fetch API, which is the modern way to query files.
Here are some examples on how to use it
If you really want to use AJAX, use this :
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Source : You Might Not Need jQuery

Javascript make HTTP request on regular interval not working

I have a page to show the chat messages. I need to refresh the chat body every 30 seconds to load the new messages. I have set the interval to 30 seconds , the function is running , but its not making the HTTP request. Here is my code
function loadmessages(){
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/'+ ids );
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function(){
if(this.status == 200){
var resp = JSON.parse(this.responseText);
console.log(resp.message);
}
else{
console.log(this.status);
}
request.send(null);
}
}
loadmessages();
setInterval(function(){
loadmessages()
}, 30000);
Consistent indentation matters. You're putting request.send(null); inside the request.onload function, so of course it never gets sent in the first place. Try putting it outside, instead:
function loadmessages() {
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/' + ids);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.responseText);
console.log(resp.message);
} else {
console.log(this.status);
}
}
request.send(null);
}

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

Catch asynchronous network error from XMLHttpRequest send()

I'm making an http request asynchronously using XMLHttpRequest:
xhr.open(method, uri, true);
When I send something:
xhr.send(something)
When the server is down, it throws the following error:
net::ERR_CONNECTION_REFUSED
How can I catch and handle this error? The standard try..catch block doesn't work as the request is asynchronous.
Thanks in advance.
Use the onerror event of the XMLHttpRequest:
function aGet(url, cb) {
var x = new XMLHttpRequest();
x.onload = function(e) {
cb(x.responseText)
};
x.onerror= function(e) {
alert("Error fetching " + url);
};
x.open("GET", url, true);
x.send();
}
var dmp = console.log.bind(console); // Dummy callback to dump to console
aGet("/", dmp) // Ok, uses onload to trigger callback
aGet("http://dgfgdf.com/sdfsdf", dmp); // Fails, uses onerror to trigger alert
I wrote a full solution to that problem. It works perfectly!
I have a function called networkOrfail which will try to resend the XMLHttpRequest each second, if the network is available. Otherwise, it'll ignore the request.
When the request is succeeded, that polling stops and the response is returned.
Here's how to detect whether the network is available:
function getNavigatorConection() {
return navigator.onLine;
}
Then, create your XMLHttpRequest:
function makeRequest() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'anypage/anotherpage', true);
xhr.timeout = 2000;
xhr.onload = function () {
// Your request is completed
if (xhr.readyState == 4 && xhr.status == 200) {
// You're in a successfully condition
}
};
xhr.ontimeout = function (e) {
// Your request timed out
};
xhr.send(null);
}
Now, define your polling method as follows:
function networkOrFail(callFunc, callTime) {
let connected = getNavigatorConection();
let callableTimes = callTime < 2000 ? 2000 : callTime;
let toursBegin = 3;
let tours = toursBegin;
let intervalId;
let request = function() {
intervalId = setInterval(function() {
let connected = getNavigatorConection();
if (tours > 0) {
if (connected) {
callFunc();
tours =0;
return false;
}
tours--;
alert("i tryied againt to resend for another time and it remain just "+tours+" to retry");
} else {
clearRequest();
tours =toursBegin;
}
}, callableTimes > 5000 ? 5000 : callableTimes);
};
let clearRequest = function() {
clearInterval(intervalId);
intervalId = null;
};
if (connected)
callFunc();
else
request();
}
Finally, call the send method through the polling method by passing it toghether with the timeout in minutes:
networkOrFail(makeRequest, 5000);

Categories