Display JSON Request - javascript

<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
</script>
</head>
<body>
</body>
</html>
My problem is simple, I have requested the JSON YouTube v3 Data API, however, I'd like to display data requested from the link: https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y Namely the subscriber count, how would I be able to use this GET request to load the number of subscribers into the innerHTML of an element? What do I have to do?

Using the object you get by parsing the JSON (data), get the subscriberCount value and place it into a div or other element using .innerHTML. Make sure you use request.send() to actually send your AJAX request.
<html>
<head>
<script>
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCiWypivJjO5CIQPVVfFlVQA&key=AIzaSyD5FVw6fP3ingbjTvUEzm-EYctX2ytfL2Y', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var data = JSON.parse(request.responseText);
document.getElementById("subs").innerHTML = data.items[0].statistics.subscriberCount;
} else {
// We reached our target server, but it returned an error
}
};
request.send();
</script>
</head>
<body>
<div id="subs"></div>
</body>
</html>

Related

Rapidapi Api request with XMLHttpRequest

this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}

How to output a String into an HTML document page from a native Function API

I am practicing my API skills and decided to make a Crypto Currency calculator (simple enough).
I have been stuck on how to output the value that I want in my HTML doc to a specific DIV "id". To the best of my knowledge everything seems like it should be working but when I try to output the desired value onto my innerHTML it outputs nothing.
I am trying to output this value {"USD":1.94} onto my HTML. However I am not skilled enough to properly call this value from its respective storage. I was hoping if anyone can help me fix this. Thank you.
Here is my HTML:
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Crypto Calc</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css" />
<!-- <script type="text/javascript" src="https://min-api.cryptocompare.com/"></script> -->
</head>
<body>
<header>
Header
</header>
<div id="pbf-main-container">
</div>
<footer>
Footer
</footer>
<script src="pbf.js"></script>
</body>
</html>
Here is the Javascript:
// Get the HTTP Header Request for CryptoCompare API
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
console.log(request.responseText); // This is the outcome of the curreny value
} else if (!isValid(this.response) && this.status == 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", 'https://min-api.cryptocompare.com/data/price?fsym=XRP&tsyms=USD' , true);
request.send(null);
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// This it to integrate it with the index.html
// console.log(XRPUSD);
document.getElementById("pbf-main-container").innerHTML = XRPUSD;
Move last five lines
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// This it to integrate it with the index.html
// console.log(XRPUSD);
document.getElementById("pbf-main-container").innerHTML = XRPUSD;
after this line
document.body.className = 'ok';
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// This it to integrate it with the index.html
// console.log(XRPUSD);
document.getElementById("pbf-main-container").innerHTML = XRPUSD;
// Get the HTTP Header Request for CryptoCompare API
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
console.log(request.responseText); // This is the outcome of the curreny value
// Putting the outcome of the HTTP request into a Variable
var XRPUSD = request.responseText;
// beautify JSON object
document.getElementById("pbf-main-container").innerHTML = JSON.stringify(XRPUSD,null,2);
} else if (!isValid(this.response) && this.status == 0) {
document.body.className = 'error offline';
console.log("The computer appears to be offline.");
} else {
document.body.className = 'error';
}
}
};
request.open("GET", 'https://min-api.cryptocompare.com/data/price?fsym=XRP&tsyms=USD' , true);
request.send(null);
Http request is async,so you

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

How to replace content in image container with new content onclick?

I'm using Giphy's API to learn how to make a random GIF generator. The code below works fine for generating one GIF and putting it in the imageContainer, but I'm wondering what I can add to make a new GIF appear in the imageContainer when the randomDog button is clicked? As it looks now, the request for more GIFs is successful if you click the button, but they are not posted in the image container since there is already a GIF in it.
This is my JavaScript:
document.addEventListener('DOMContentLoaded', function () {
request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cute+dog', true);
document.getElementById("randomDog").onclick = function () {
if (request.status >= 200 && request.status < 400){
data = JSON.parse(request.responseText).data.image_url;
console.log(data);
document.getElementById("imageContainer").innerHTML = '<center><img src = "'+data+'" title="GIF via Giphy"></center>';
} else {
console.log('reached giphy, but API returned an error');
}
};
request.onerror = function() {
console.log('connection error');
};
request.send();
});
And this is my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel= "stylesheet" type="text/css" href="dogstyle.css">
<meta charset="UTF-8">
<title>Sadness be gone!</title>
</head>
<body>
<div id="headers">
<h1> Having a bad day?</h1>
<h1> Not anymore! </h1>
</div>
<h3 id="subheader">Happiness and fluffyness is just a click away</h3>
<div id="imageContainer"></div>
<button id="randomDog" class="button">Click away!</button>
<script src="js/experiment.js"></script>
</body>
Thanks in advance!
Just move the lines initializing and sending the XMLHttpRequest inside of the click handler, and include the success function inside an onreadystatechange event handler.
(Note that the API key you are using returns an error for me when I use it in a snippet; unsure of how I would fix that but maybe it will work on your end.)
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("randomDog").onclick = function() {
request = new XMLHttpRequest;
request.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cute+dog', true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.responseText).data.image_url;
console.log(data);
document.getElementById("imageContainer").innerHTML = '<center><img src = "' + data + '" title="GIF via Giphy"></center>';
} else {
console.log('reached giphy, but API returned an error');
}
}
}
request.onerror = function() {
console.log('connection error');
};
request.send();
};
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="dogstyle.css">
<meta charset="UTF-8">
<title>Sadness be gone!</title>
</head>
<body>
<div id="headers">
<h1> Having a bad day?</h1>
<h1> Not anymore! </h1>
</div>
<h3 id="subheader">Happiness and fluffyness is just a click away</h3>
<div id="imageContainer"></div>
<button id="randomDog" class="button">Click away!</button>
<script src="js/experiment.js"></script>
</body>
Try this
....
document.getElementById("randomDog").onclick = function () {
if (request.status >= 200 && request.status < 400){
data = JSON.parse(request.responseText).data.image_url;
console.log(data);
// Clear the existing image first
document.getElementById("imageContainer").removeChild(document.getElementsByClassName("mygif")[0]);
// Now set the new image in image container
document.getElementById("imageContainer").innerHTML = '<center><img class="mygif" src = "'+data+'" title="GIF via Giphy"></center>';
} else {
console.log('reached giphy, but API returned an error');
}
};
....

AJAX XHR request onReadyStateChange events order and number of times clarification

I'm learning and trying to write a simple stock quote tool using Python-Flask and Javascript.
I specifically want to learn plain Javascript. My code is working, but what I don't understand is when I'm watching the developer console, I get 3 error messages printed before I get the successful console.log(response).
Is it simply that the code loops 3 times before the response comes back, so it logged 'ERROR' each of those times before finally returning the 200 status? Would someone explain it to me or point me to a good article/post?
My event listener:
document.getElementById("btn_quote").addEventListener("click", getQuote);
The ajax call:
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value
var shares = document.getElementById("shares").value
var url = "/quote/"+ticker+"/"+shares
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
console.log(response);
}
} else {
// TODO, handle error when no data is available.
console.log('ERROR');
return false;
}
};
request.open('GET', url);
request.send();
}
It's not returning separate HTTP status codes, its returning different ready states.
Change your console.log("ERROR");. To console.log(request.readyState);.
Then you will see what it is reporting and why.
i think you should be checking your readyState values with the actual values of the response. For you reference, following are the possible values of readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
So you could basically check it to be 4 in your case:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
//response statements
} else {
//error statements
}
};
Basically, ajax calls will get notified for the following events which is called as readyStateChange event.
For most cases, you used to get 4 ready state changes based on the speed of the connection (rare cases only only one if it's very quick) and you should check whether it is 4 which means the response is completed now.
To check whether the request is suceess or not, you should check the request.status === 200 which means success and can check for other http status code for errors like 404, 500 etc.
document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
function getQuoteError(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow404.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />

Categories

Resources