onreadystatechange only firing once - javascript

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));
}
}
};
}
}

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

clearInterval not working with XMLHttpRequest

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.

A partial build of jQuery just for $.ajax (XMLHttpRequest) functionality?

Is there a way to obtain or compile a stripped down version of jQuery, that just contains the $.ajax function, and anything that it depends on?
NOTE:
Background: Wish to create a script which includes just this function in-lined within my own (with proper attributions of course)
Including the entire jQuery would be overkill for my requirements
A great example of what I am looking for is Modernizr:
http://modernizr.com/download/
The download page allows you to select which parts you want, and it will work out the dependencies, and give your a partial build, containing just what you have asked for.
Why do you even need jQuery?
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
// Success! run your success function
resp = this.responseText;
} else {
// Error :( run your error function
}
}
};
request.send();
request = null;
Or a POST:
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
// Success! run your success function
resp = this.responseText;
} else {
// Error :( run your error function
}
}
};
request.send(data);
request = null;
Taken from here, a fantastic resource for Vanilla JS alternatives to jQuery. This should work with IE8+.

onreadystatechange is never getting called

I have created XHR and I am also getting response from server correctly.
But for some reason the callback is not happening. Please help.
function uploadDr(){
var url = "UploadExcelServlet";
if (req != null) {
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.onreadystatechange = callBk;
req.setRequestHeader("Content-Type", "multipart/form-data");
req.send();
} else {
alert("Null Request");
}
}
function callBk(){
if (req.readyState == 4){
if (req.status == 200){
alert(req.responseXml);
} else {
alert(req.statusText);
}
}
}
For GET requests you don't need set the "Content-Type" header, because the data are always passed in the URL.
And maybe you need set request data to send as follows:
req.send(null);
Then test readyState in callback function:
function callBk(){
console.log(req.readyState); // don't stop the script by using alert!
// other stuff
}
Make shure that readyState is not equal to 0 (XMLHttpRequest.UNSENT).

Categories