I have a website (wagtail CMS) running at AWS at domain:8000 and my API running at domain:8801
On my webpage I try to get some info from API by using JS (Access-Control-Allow-Origin header is set correctly at API, it's a django-based app)
Unfortunately the following code returns only xhr.status = 0 and empty responseText no matter what I try to access.
When I put domain:8000 at xhr.open('GET','http://domain:8000',true) everything works just fine, I see my html code.
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
On the API side I see all my requests, status=200 in server console.
You're supposed to use a callback function to catch the response from a request using the XMLHttpRequest object. Do something like this instead:
xhr.addEventListener('readystatechange', function() {
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
} else {
alert( "SUCCESS" );
}
}
});
Look here for docs and an examples on doing that.
You need to wait for xhr.readyState == 4 before xhr.status is at all valid (actually I think it's valid at 3, but lets keep consistent with 99.999% of code in the wild)
function load() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain:8801/api/', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status != 200) {
alert( "ERR" ); --always ERR in browser
}
else {
alert( "SUCCESS" );
}
}
};
xhr.send();
}
Related
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);
}
};
I am new to HTML with JavaScript:
My code is:
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.status);
}
else{
alert(xhr.status);
}
}
xhr.open('GET', "http://localhost:8080/hello", true);
xhr.send();
I always get xhr.status as 0? I an testing with Chrome and Edge. What is the issue?
You're looking at xhr.status before the request is complete. Only check status when readyState is 4:
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
// All good
console.log(xhr.status);
}
else {
// Something went wrong
alert(xhr.status);
}
}
}
xhr.open('GET', "http://localhost:8080/hello", true);
xhr.send();
That said, on all major browsers, XMLHttpRequest is obsolete. Instead, use fetch:
fetch("http://localhost:8080/hello")
.then(response => {
if (!response.ok) {
throw new Error(response.status);
}
})
.then(response => {
// Read the body of the response
return response.text(); // or .json(), .arrayBuffer(), .blob(), .formData()
})
.then(data => {
// All good, use the data
})
.catch(error => {
// Handle the error
});
If you prefer, instead of using the .text, .json, etc. helpers, you can use response.body, which is a ReadableStream.
You've said you're still getting a status of 0 with the updated code. The only way I can see that happening is if you're making a cross-origin request and being prevented by the Same Origin Policy. You should be getting a fairly clear error in the web console. If that's the case, look into CORS (if you control the other end) or JSONP or using a server to make the request for you. There's a lot of information about the SOP and CORS out there.
I generally have been using XMLHttpRequest to perform Ajax calls. However, when the server has an error, I'd like to console.log the error so that I don't have to run to the server to see the event log there.
Here's what I generally do:
function LoadPage(){
var parameters="this=that";
var x = new GetXmlHttpObject();
x.open("POST", "Ajax.aspx?Function=LoadPage")
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.ontimeout = function () { location.reload(true); }
x.send(parameters);
x.onreadystatechange = function () {
if (x.readyState === 4 && x.status === 200){
//Do Stuff with the response
}
}
But if the server has an error with the request, I get the error on the x.send(parameters) line. I've tried to wrap that in a try..catch, but the error comes up in the console even with the command held inside the try.
How can I console.log the 500 errors from the server using this structure?
But if the server has an error with the request, I get the error on the x.send(parameters) line.
That won't happen. The client can't react to the response in any way before the response has arrived.
I've tried to wrap that in a try..catch
That won't work for two reasons.
It is asynchronous
It doesn't throw an exception
if (x.readyState == 4 && x.status == 200){
You're already testing for a 200 status here. Test for a 500 status in the same way.
Updated function
function LoadPage() {
return new Promise(function(succeed, fail) {
var req = new XMLHttpRequest();
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.open("POST", "Ajax.aspx?Function=LoadPage", true);
req.ontimeout = function () { location.reload(true); }
req.addEventListener("load", function() {
if (req.status < 400)
succeed(req.responseText);
else if (req.status == 500)
fail("Error 500: Internal Server Error");
else
fail(new Error("Request failed: " + req.statusText));
});
req.addEventListener("error", function() {
fail(new Error("Network error"));
});
req.send("this=that");
});
}
Usage:
LoadPage().then(function(text) {
console.log("data.txt: " + text);
}, function(error) {
console.log("Failed to fetch data.txt: " + error);
});
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));
}
}
};
}
}
I am writing a function to grab a json file from a website/server and save it in local storage with the code:
function donators() {
var jsonURL = "http://mywebsite.com/donators.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", jsonURL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
localDataStore.set("fb_donators", xhr.responseText);
}
};
xhr.send();
}
The above code works perfectly fine when the json file can be reached, but if my server goes down and the file cannot be reached my script halts at the line with xhr.send() with the error:
GET http://mywebsite.com/donators.json net::ERR_NAME_NOT_RESOLVED
Is there a way I can detect check if url can be reached before the send request to stop the send the request and allow the rest of my script to continue to run instead of getting halted at xhr.send()?
Thanks!
You can use a try block for this. It still requires the HTTP request, but it will fail gracefully and you can handle the error any way you'd like.
function donators() {
var jsonURL = "http://mywebsite.com/donators.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", jsonURL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
localDataStore.set("fb_donators", xhr.responseText);
}
};
xhr.timeout = 5000;
xhr.ontimeout = function() {
alert( 'The operation timed out.' );
}
try { xhr.send(); } catch( err ) {
alert( 'Error getting data: ' + err.message );
}
}