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.
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'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
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 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();
}
I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.
Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?
You can get it by XMLHttpRequest.responseText in XMLHttpRequest.onreadystatechange when XMLHttpRequest.readyState equals to XMLHttpRequest.DONE.
Here's an example (not compatible with IE6/7).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
Use fetch!
It is much more readable and easily customizable. All modern browsers and Node support it. Here is a more in depth tutorial
const url = "https://stackoverflow.com";
fetch(url)
.then(
response => response.text() // .json(), .blob(), etc.
).then(
text => console.log(text) // Handle here
);
You can optionally pass a second param, depending on the needs/type of request.
// Example request options
fetch(url, {
method: 'post', // Default is 'get'
body: JSON.stringify(dataToPost),
mode: 'cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(response => response.json())
.then(json => console.log('Response', json))
In Node.js, you'll need to import fetch using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url)
.then(response => response.json())
.catch((e) => {});
More Info:
Matt Walsh Tutorial
Mozilla Documentation
Can I Use
The simple way to use XMLHttpRequest with pure JavaScript. You can set custom header but it's optional used based on requirement.
1. Using POST Method:
window.onload = function(){
var request = new XMLHttpRequest();
var params = "UID=CORS&name=CORS";
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('POST', 'https://www.example.com/api/createUser', true);
request.setRequestHeader('api-key', 'your-api-key');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
}
You can send params using POST method.
2. Using GET Method:
Please run below example and will get an JSON response.
window.onload = function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
request.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
request.send();
}
In XMLHttpRequest, using XMLHttpRequest.responseText may raise the exception like below
Failed to read the \'responseText\' property from \'XMLHttpRequest\':
The value is only accessible if the object\'s \'responseType\' is \'\'
or \'text\' (was \'arraybuffer\')
Best way to access the response from XHR as follows
function readBody(xhr) {
var data;
if (!xhr.responseType || xhr.responseType === "text") {
data = xhr.responseText;
} else if (xhr.responseType === "document") {
data = xhr.responseXML;
} else {
data = xhr.response;
}
return data;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log(readBody(xhr));
}
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);