Reputation: 41
The following code is supposed to simply alert me with the value that I am wishing to get from a JSON file. The problem is it doesn't give me anything back :(. Below is the link for the JSON file:
https://rest.soilgrids.org/query?lon=5.39&lat=51.57
In case you don't know, the Soil Grids API is an API used for giving you soil insight on a certain latitude and longitude of land mass.
I have to admit, I don't know what is wrong. Below is my code:
var soil = new XMLHttpRequest();
function testFunction (){
soil.open("REST", "https://rest.soilgrids.org/query?lon=5.39&lat=51.57", false);
soil.send(null);
var r = JSON.parse(soil.response);
var majorreal = r.properties.TAXNWRBMajor;
alert(majorreal);
}
<button onclick="testFunction()">Submit</button>
Whenever the program is run, I get a send error with the XMLHttpRequest...
"Uncaught NetworkError: Failed to execute 'send' on
'XMLHttpRequest': Failed to load 'https://rest.soilgrids.org/query
lon=5.39&lat=51.57'.",
Any help would be appreciated ;).
Upvotes: 0
Views: 1800
Reputation: 1941
A common convention is to follow the pattern below. This allows you to do something with the result when its is done by checking for the ready state property.
function testFunction (){
var soil = new XMLHttpRequest();
soil.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
soil.open("GET", "https://rest.soilgrids.org/query?lon=5.39&lat=51.57", false);
soil.send(null);
}
Upvotes: 0
Reputation: 196002
The problem is that there is no REST
method (see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open).
Using GET
works.
var soil = new XMLHttpRequest();
function testFunction (){
soil.open("GET", "https://rest.soilgrids.org/query?lon=5.39&lat=51.57", false);
soil.send(null);
var r = JSON.parse(soil.response);
var majorreal = r.properties.TAXNWRBMajor;
alert(majorreal);
}
<button onclick="testFunction()">Submit</button>
Also there is no reason to use synchronous calls.
Upvotes: 3