Onloading webpage spinner (loading) doesn't stop in the browser tab? - javascript

On loading webpage the spinner should stop in browser but it doesn't it keeps on spinning how can I stop this.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var requestURL = "https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b";
var request = new XMLHttpRequest();
request.open('GET',requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var myjsondata = request.response;
console.log(myjsondata);
showdata(myjsondata);
}
function showdata (data) {
var str = data.articles[0].title;
document.write(str + "<br> <br>");
var img = data.articles[1].description;
document.write(img);
}
</script>
</body>
</html>
You can check this image ->

Related

Return a html img tag in javascript

I'm doing a simple project where I'm showing my github profile in vanilla javascript.
let requestURL = 'https://api.github.com/users/fcfidel';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var githubInfo = request.response;
populateHeader(githubInfo);
//showGithubInfo(githubInfo);
}
function populateHeader(jsonObj) {
var myH1 = document.createElement('h1');
//myH1.textContent = jsonObj['login'];
myH1.textContent = `<img src="${jsonObj['avatar_url']}" />`;
image.appendChild(myH1);
var myPara = document.createElement('p');
myPara.textContent = 'Name: ' + jsonObj['name'] + ' // Formed: ' + jsonObj['created_at'];
image.appendChild(myPara);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="application/javascript" src="main.js"></script>
</head>
<body>
<div class="image"></div>
<div class="name"></div>
<script>
var image = document.querySelector('.image');
var name = document.querySelector('.name');
</script>
</body>
</html>
I am trying to find a way to return the in javascript but I just can't find a way :(
The only way I kind of found a way was with the template literal
it works but not that way I want, it does return what I want but...
this is the result:
I know the solution is something really simple, but I just can't even no more...
this is the result that I want:
Im learning javascript Im still a noob... Im doing the exercises from the MDN :/
Set the image source instead of adding it to the div. Also the backticks are not helping!
Add image tag and modify the ajax call to use:
document.querySelector('#my-image').src = jsonObj['avatar_url'];
let requestURL = 'https://api.github.com/users/fcfidel';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var githubInfo = request.response;
populateHeader(githubInfo);
//showGithubInfo(githubInfo);
}
function populateHeader(jsonObj) {
var myH1 = document.createElement('h1');
//myH1.textContent = jsonObj['login'];
//myH1.textContent = `<img src="${jsonObj['avatar_url']}" />`;
//image.appendChild(myH1);
var myPara = document.createElement('p');
myPara.textContent = 'Name: ' + jsonObj['name'] + ' // Formed: ' + jsonObj['created_at'];
image.appendChild(myPara);
document.querySelector('#my-image').src = jsonObj['avatar_url'];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="application/javascript" src="main.js"></script>
</head>
<body>
<div class="image">
<img id="my-image" src="" />
</div>
<div class="name"></div>
<script>
var image = document.querySelector('.image');
var name = document.querySelector('.name');
</script>
</body>
</html>

JSON data to HTML using AJAX

I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.
`enter code here`
<html lang="en">
<head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
<p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
function renderHTML(data) {
var output = "";
for (var key in data)
{
output += "<p>" + key + output + "</p>"
}
}
};
</script>
</body>
The main issue is how your calling the api "http://api.fixer.io/latest".rates
You call rest endpoints by there address params or with query params.
Please see example below calling your specified endpoint. That should get you started
var myData = 'https://api.fixer.io/latest'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(xhttp.responseText)
Object.keys(res.rates).forEach((e)=>{
console.log(`${e}: ${res.rates[e]}`)
//Add your stuff here
})
}
};
xhttp.open("GET", myData, true);
xhttp.send();

displaying images using file reader and blob

I want display a set of thumbnail images using fileReader api of javascript.I will send requests to my server and it will respond with a stream of bytes.I am sending requests through native xhr methods.But its not displaying any images.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
<script>
var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
(function(){
for(var i=0;i<thumbURL.length;i++){
var oReq = new XMLHttpRequest();
oReq.open("GET", thumbURL[i]);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
if (this.status == 200) {
var fileReader = new window.FileReader();
fileReader.readAsDataURL(this.response);
var response=fileReader.result;
$("#thumbnails").append("<img src="+response+"></div>");
}
};
oReq.send();
}
})();
</script>
</head>
<body>
<div id="thumbnails"></div>
</body>
</html>
Any help will be greatly appreciated.Thanks in advance.
UPDATE:correct solution
<html>
<head>
<script type="text/javascript" src="/js/jquery-2.1.1.js"></script>
<script>
var thumbURL = ['https://domainname.com/api/th/1','https://domainname.com/api/th/2','https://domainname.com/api/th/3','https://domainname.com/api/th/4','https://domainname.com/api/th/5','https://domainname.com/api/th/6'];
(function(){
for(var i=0;i<thumbURL.length;i++){
var oReq = new XMLHttpRequest();
oReq.open("GET", thumbURL[i]);
oReq.responseType = "blob";
oReq.onload = function(oEvent) {
if (this.status == 200) {
var filereader=new window.FileReader();
filereader.readAsDataURL(this.response);
filereader.addEventListener("load",function() {
var response=filereader.result;
$("#thumbnails").append("<img src="+response+"></div>");
},false);
}
};
oReq.onerror=function(e){
alert("error");
};
oReq.send();
}
})();
</script>
</head>
<body>
<div id="thumbnails"></div>
</body>
</html>
The FileReader API is asynchronous so you have to add a load handler and when triggered, then add the result:
var fileReader = new window.FileReader();
fileReader.onload = function() { // need load handler
var response=this.result;
$("#thumbnails").append("<img src="+response+"></div>");
};
fileReader.readAsDataURL(this.response);
I would in any case recommend to skip the conversion part. Using the blob directly not only saves memory, but is much faster. You just have to create the image element manually, for example:
oReq.onload = function(oEvent) {
if (this.status === 200) {
var img = new Image;
img.src = (URL || webkitURL).createObjectURL(this.response);
$("#thumbnails").append(img); // todo: append the </div> separately
}
};

SoundCloud: Search & display results using Javascript

I've created the code below, but it is not working properly. Where have I gone wrong and or what did I forget to include?
var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
function results() {
console.log(search);
xhr.send()
}
document.getElementById("results").innerHTML = results();
// Send the XHR
xhr.open('GET', 'https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search;', true);
<html>
<head>
<!-- JS -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="search" id="search" />
<button onclick="results()">Search</button>
<p id="results"></p>
</body>
</html>
Your code will run on page-load but you want to create an event listener that waits for your user to press Search and then execute your request.
Try:
$('#search').click(function(){
var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
var results = xhr.open('GET', 'https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search;', false);
document.getElementById("results").innerHTML = results;
})
The 'false' parameter in the xhr request prevents the code from running asynchronously but I am sure you could somehow use callbacks?
Figured it out...
function audioResults(){
var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search, false);
xhr.addEventListener("load", function() {
document.getElementById("results").innerHTML = xhr.response;
}, false);
xhr.send();
}
<html>
<head>
<!-- JS -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="search" id="search" />
<button onclick="audioResults()">Search</button>
<p id="results"></p>
</body>
</html>

Convert API request to text to use in site

I am trying to make an API request and put the return in a div.. What am I doing wrong?
<!DOCTYPE HTML>
<html>
<head>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.send();
xhr = function() {
document.getElementById("myDiv").innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
You need to bind onto the onload listener instead of setting a value to xhr:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.onload = function() {
document.getElementById("myDiv").innerHTML=this.responseText;
};
xhr.send();
See the MDN docs on Using XMLHttpRequest.
You need
xhr.onload = function() { //onload
document.getElementById("myDiv").innerHTML=xhr.responseText;
}

Categories

Resources