Reputation: 39
I am trying to fetch data by making an api call however the browser keeps showing xhr failed loading. i cant understand the mistake in my code.
function letsgo()
{
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','https://newsapi.org/v1/articles?source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58',true);
ourRequest.onload = function()
{
if (ourRequest.status >= 200 && ourRequest.status < 400)
{
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
}
else
{
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
below is the function which logs the data
function renderHTML(data) {
console.log(data);
}
Upvotes: 0
Views: 4774
Reputation: 2352
Your method of fetching data is a bit old, recently all major browsers are supporting fetch
api
You can use it like:
fetch('https://newsapi.org/v1/articles?source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58')
.then(r => r.json())
.then(data => {
document.getElementById("root").innerText = JSON.stringify(data, 0, 2)
})
<pre id="root">
</pre>
Upvotes: 1
Reputation: 127
Here is sample Code. This Codes works fine.
<html>
<link rel="stylesheet"
href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<body>
<script>
$(document).ready(function () {
function renderHTML(data) {
console.log(data);
}
function letsgo() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',
'https://newsapi.org/v1/articles?
source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58',
true);
ourRequest.onload = function () {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned
an error.");
}
};
ourRequest.onerror = function () {
console.log("Connection error");
};
ourRequest.send();
}
letsgo();
})
</script>
</body>
</html>
Upvotes: 1