this is my project: http://cryptotipsitalia.sytes.net/.
I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price.
How can I add it?
That's my code:
function getValueBTC() { <!-- chiamata API --> /
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
var output;
console.log(url);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
var obj = JSON.parse(output);
var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */
document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.send();
}
let price = require('crypto-price');
price.getCryptoPrice('EUR', 'ETH').then(obj => {
console.log(obj.price); // It will print ETH rate per BTC
document.getElementById("cellaValoreETH").innerHTML = obj.price;
}).catch(err => {
console.log(err);
});
table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table>
Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work?
How can I add obj.price in my HTML code?
Thanks
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to implement JavaScript tool for generating a random video from specific channel from youtube, I coded everything and it works fine in the console, however I cannot save the value in variable and to display the video later on my website. Is it possible to make the value of x (defined on the end of the pasted code) have the value of youtubeUrl
function getVideo() {
var channelId = "";
var apiKey = "";
var videosUrl = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelId + "&maxResults=50&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videosUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var videos = json.items;
var randomNumber = Math.floor(Math.random() * (videos.length + 1));
var randomVideo = videos[randomNumber];
var videoId = randomVideo.id.videoId;
var videoUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&part=snippet,contentDetails,statistics&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videoUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var singleVideo = json.items[0].id;
var youtubeUrl = "https://www.youtube.com/embed/" + singleVideo;
}
};
}
};
}
let x = getVideo(); // how to make it such that x has the value of youtubeUrl
Just wrap the content of your function inside a new Promise constructor and resolve it with the youtubeUrl:
function getVideo() {
return new Promise((resolve, reject) => {
var channelId = "";
var apiKey = "";
var videosUrl = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelId + "&maxResults=50&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videosUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var videos = json.items;
var randomNumber = Math.floor(Math.random() * (videos.length + 1));
var randomVideo = videos[randomNumber];
var videoId = randomVideo.id.videoId;
var videoUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&part=snippet,contentDetails,statistics&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videoUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var singleVideo = json.items[0].id;
var youtubeUrl = "https://www.youtube.com/embed/" + singleVideo;
resolve(youtubeUrl);
}
};
}
};
}
let x = await getVideo();
There's an issue with my function in the AJAX.
I create an AJAX call to a PHP file that returns JSON.
For loop this JSON I created a fucntion that I run if the AJAX is successfull.
But in practice the data is empty.
<script>
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display(this.responseText);
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}
</script>
If I code the JSON hardcode in the function like this than everything is okay.
var hardcoded = {"1736":{"id":"1736","post_title":"Test explode","_sku":"12345","_stock":null,"_price":"9.50"}}
//PART OF THE CODE
if (this.readyState == 4 && this.status == 200) {
display(hardcoded);
}
How can I fix this that the function use the responded JSON?
here is a corrected script, You should just convert the responseData from string to Json Object!
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display( JSON.parse(this.responseText) ); // You should convert the response from string to a valid JSON
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}
How can I loop my json file using my script, eg: I should choose whether to loop Schema A or Schema B.
My json file is:
{
"A":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
],
"B":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
]
}
Maybe setting a variable so as to define the scheme I have to display
My javascript file is:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj= JSON.parse(this.responseText);
myFunction(obj, 'A');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj, key) {
var arr = obj[key];
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
Assuming that what you presented as JSON file is a response form network and is passed to myFunction, then why not to do something like:
let myRootArray;
if(/* some confitions */) {
myRootArray = myArr.A
} else {
myRootArray = myArr.B
}
myFunction(myRootArray );
Beside that, your names are a bit confusing, var myArr = JSON.parse(this.responseText);, while JSON.parse will return object, not an array.
I have the following code, which works (sort of). When I run it, the page displays information about the two coins, but returns 'undefined' for the coin price. The call to alert() indicates that the getCoinPrice function is running AFTER the main code. How do you execute the code so that the function call happens serially? If that's not possible, would it be better to learn to use the Fetch API?
Here's the code, in its entirety:
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p id="demo"></p>
<script>
function getCoinPrice(id) {
var xhr = new XMLHttpRequest();
var URL = "https://api.coinmarketcap.com/v2/ticker/" + id + "/";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var Obj = JSON.parse(xhr.responseText);
var price = Obj.data.quotes.USD.price;
alert(price);
return(price);
}
}
xhr.open("GET", URL, true);
xhr.send();
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var coins = [ "BTC","ETH" ]
for(j=0; j < coins.length; j++) {
for(i=0; i < myObj.data.length; i++) {
if (myObj.data[i].symbol == coins[j]) {
document.getElementById("demo").innerHTML +=
myObj.data[i].id + "," + myObj.data[i].name + "," +
myObj.data[i].symbol + "," +
getCoinPrice( myObj.data[i].id ) + "<br>" ;
}
}
}
}
};
xmlhttp.open("GET", "https://api.coinmarketcap.com/v2/listings/", true);
xmlhttp.send();
</script>
</body>
</html>
Posting this because I found a lot of jquery answers, but no raw javascript answers.
So I have a function to post a comment to a comment section, and I want the comment section to refresh after posting a comment, But for some reason my code isn't working.
The code for loading the comment section:
function loadCommentSection() {
console.log("loading section")
imgid = imgid.replace("img/pic (", "");
imgid = imgid.replace(").jpg", "");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("commentsection").innerHTML = this.responseText;
}
};
xhttp.open("GET", "commentsection.php?imgid=" + imgid, true);
xhttp.send();
}
and the code for submitting the comment:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
loadCommentSection();
}
The problem is that the loadCommentSection function in the submitComment function isn't executing.
You should allow the comment to be sent to the server and be registered before calling loadCommentSection. So, it is probably best to call it when the response becomes available:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
loadCommentSection(); // <<---- moved here.
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
}