How to get REST API JavaScript fetch object value to HTML? - javascript

How can I get printed console object value to HTML?
I have JavaScript fetch code like this:
const comments = fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1")
.then((response) => response.json())
.then((labels) => {
return labels.comments;
});
const printComments = () => {
comments.then((number) => {
console.log(number);
});
};
printComments()
printComments() numeric object value shows correct in console, but how to show it in HTML
to <span id="comments">..</span> ?

With JS you can edit the DOM Hierarchy by searching for your desired Element to change.
const commentsEl = document.querySelector('.comments');
commentsEl.innerHTML = printComments();
With document.querySelector(CSS-Selector) you can search the DOM-Tree for a sufficient Element matching your Selector
We store the Element in a variable and change the Content of this Element by saving the comments in the property .innerHTML.
I've added a snippet demonstrating the changes below, and also changed some bits to improve your code.
As the fetch-Method is asynchronous, you’ll see fetching comments ... for a brief moment, as we change the content when the fetch finished and we got the results.
const commentsEl = document.querySelector('.comments');
// We fetch the comments as before
fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1")
.then((response) => response.json())
.then((labels) => {
// But when we get the results, we immedietly change the contents of the comments span.
commentsEl.innerHTML = labels.comments;
});
<div class="container">
<p>Comments:</p>
<span class="comments">Fetching comments ...</span>
</div>

You could try setting a p tag with an id, ex: <p id=“comments”>and then using document.getElementById(“comments”).innerValue = number;
Place that second piece of code into printComments()

First you need to get your span tag in your html document.
Then define the innerHtml property of the span element by the value returned by the promise, in this case in your case the value is returned through a callback, so you simply have to perform the process in the scope of the callback.
Here is a snippet to illustrate this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span id="comments"></span>
<script>
const span = document.getElementById("comments");
const comments = fetch("https://api.github.com/repos/pieceofdiy/comments/issues/1")
.then((response) => response.json())
.then((labels) => {
return labels.comments;
});
comments
.then(res => span.innerHTML = res)
.catch(err => console.log(err));
</script>
</body>
</html>
But it can be done more cleanly this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ol>
<li>Comments: <span id="comments1"></span></li>
<li>Comments: <span id="comments2"></span></li>
<li>Comments: <span id="comments3"></span></li>
</ol>
<script>
const comments1 = document.getElementById("comments1");
const comments2 = document.getElementById("comments2");
const comments3 = document.getElementById("comments3");
const printComment = async (url, HTMLTag) => {
try {
const request = await fetch(url);
const response = await request.json();
HTMLTag.innerHTML = response.comments;
} catch (error) {
console.log(error);
}
};
printComment("https://api.github.com/repos/pieceofdiy/comments/issues/1", comments1);
printComment("https://api.github.com/repos/pieceofdiy/comments/issues/1", comments2);
printComment("https://api.github.com/repos/pieceofdiy/comments/issues/1", comments3);
</script>
</body>
</html>
Good luck !

Related

Why does my button not fire the onclick function after i search for it with a querySelector

Basic HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class = "hitknop">Hit!</button>
</body>
<script src="index.js" defer></script>
</html>
My JS
const deckinit = "https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1";
const hitknoppie = document.querySelector("hitknop");
let deckId;
async function deckophalen(){
const response = await fetch (deckinit);
const deckopties = await response.json();
deckId = deckopties.deck_id;
console.log(deckId);
}
deckophalen();
hitknoppie.onclick = async function (){
const kaartlink = `https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`;
const response = await fetch (kaartlink);
const kaart = await response.json();
console.log(kaart);
}
I was expecting it to show the result of a single card, but it now just gives me the error that I cannot set properties of null setting 'onclick'.
I tried moving the script tag and adding defer to my Js document without success.
You must add . because you are calling a class. It must look like this:const hitknoppie = document.querySelector(".hitknop");

How to get only an specific piece of json data

This is my first time with javascript, I know Its awful hahaha
I'm looking for a way to display only the currentDateTime value from the json, the number after the T to be more specific, when clicking the button, but everytime I click on the button, It displays all the json data. Is there a better way to do this, I mean, a correct way?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>World Clock</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="msg">World Clock</h1>
<p class="dsc">Click one of the buttons to see the current time</p>
<button class="btn1" onclick="estFunc()">Eastern Standard Time (EST)</button>
fetch('http://worldclockapi.com/api/json/est/now')
.then(response => response.json())
.then(data => time = data)
.then(() => console.log(time["currentDateTime"]))
function estFunc() {
const obj = {time};
const estJson = JSON.stringify(obj);
document.getElementById("est").innerHTML = estJson;
}
const estFunc = async () => {
const response = await fetch('http://worldclockapi.com/api/json/est/now', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json(); //extract JSON from the http response
// do something with JSON
document.getElementById("est").innerHTML = data.currentDateTime;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>World Clock</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 class="msg">World Clock</h1>
<p class="dsc">Click one of the buttons to see the current time</p>
<button class="btn1" onclick="estFunc()">Eastern Standard Time (EST)</button>
<div id="est"></div>
</body>
</html>
The other answers are not wrong but don't provide an explanation on what's wrong.
Your problem is that you stringify the whole object you get from the server, not just the currentDateTime.
fetch('http://worldclockapi.com/api/json/est/now')
.then(response => response.json())
.then(data => time = data.currentDateTime.time) // only assign currentDateTime.time instead of everything
.then(() => console.log(time.currentDateTime.time))

How can I get the value to change on each click in JS?

So I retrieve a list of data and each piece of data has an ID provided by SQL. The ID is stored in a tag, and I extract the ID from the tag using innerHTML.
I have an event handler that will delete the element on click based on its ID, But after I click delete on my first element, the innerHTML value remains the same. For example, say the ID of the first element was 10, once I click delete, it will delete it. But once I click delete on the element with the ID of 11, it still says the value is 10 and will NOT delete the element with the ID of 11.
I've tried changing the P element between ID and class. I have tried to use .textContent and getElementById() With my click handler. But they all have given the same result.
This is the code for generating the HTML from GET request.
getMoviesBtn.addEventListener('click', async(e) => {
e.preventDefault();
await axios.get('http://localhost:5000/movies/retrieve-movies')
.then( res => {
console.log(res.data)
const movieList = res.data
for (let i = 0; i<movieList.length; i++) {
const sections = document.createElement('section')
sections.innerHTML = `
<p class='id'> ${movieList[i].id} </p>
<p> Title: ${movieList[i].title} </p>
<p> Runtime: ${movieList[i].runtime} </p>
<p> Release date: ${movieList[i].releaseDate} </p>
<button class="delete-btn">Delete</button>
`
divMovieList.appendChild(sections);
}
});
});
This is the code for deleting the movie entry.
// Delete movie
document.addEventListener('click', async(e) => {
e.preventDefault();
if(e.target && e.target.textContent === 'Delete') {
// Reset the notification bar to be displayed again
resetNotification();
let movieToDeleteID = document.querySelector('.id').innerHTML;
console.log(movieToDeleteID)
await axios.post('http://localhost:5000/movies/delete', {movieToDeleteID})
.then( response => {
showNotification(response);
})
.catch(err => console.error(err));
}
})
The HTML i'm using is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="./css/main.css"></link>
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600&display=swap" rel="stylesheet">
<title>Document</title>
</head>
<body>
<div id="notification">
<a id="close"> Close </a>
</div>
<nav>
Create Movie
</nav>
<div id="get-movies-btn-div">
<button id='get-movies-btn'>Get all movies</button>
</div>
<div id='movie-list'></div>
<script src="../node_modules/axios/dist/axios.min.js"></script>
<script src="movieList.js"></script>
</body>
</html>
Thank you for the help!
But after I click delete on my first element, the innerHTML value
remains the same.
That's because you're not setting the innterHTML to empty text. You could set it to empty text based on the successful response of axio.
let movieToDelete = document.querySelector('.id');
let movieToDeleteID = movieToDelete.movieToDeleteID
console.log(movieToDeleteID)
await axios.post('http://localhost:5000/movies/delete', {movieToDeleteID})
.then( response => {
...
movieToDelete.innerHTML = "";
//Or, movieToDelete.parentNode.removeChild(movieToDelete);
})
.catch(err => console.error(err));
}

How do I extract data from a 3rd party api and display it on my page with javascript?

I need to be able to fetch invoice data from this api: https://apidoc.qoyod.com/
and display it on my page through javascript. First, the user enters an api key and then the page displays the invoice index and details.
This is the code I have so far:
function displayData()
{
const div = document.getElementById("result");
const URL = 'https://www.qoyod.com/api/2.0/invoices/1';
fetch(URL)
.then((resp) => resp.json())
.then(function(data)
{
let invoices = data.results;
invoices.map(function(invoice){
let p = document.createElement('p');
p.innerHTML=`${invoice.index}`;
div.appendChild(p);
})
})
.catch(function(error) {
console.log(json.stringify(error));
})
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Qoyod Assignment</title>
<link href="styles.css" rel="stylesheet">
<script type="text/javascript" src="scripts.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="root">
<input style="float: left; margin-right: 10px;" type="text" placeholder="Enter API Key" />
<button onClick="displayData();" >Display Data</button>
<div id="result"></div>
</body>
</html>
The challenge here is the "fetch" part. I am sure there is something I am missing out on while extracting the data. Maybe I'm not using the API URL correctly? I just can't seem to be able to "grab" the API data into my"data" object. When I click the button, I get no output at all!
Also, I need to figure out how to use the entered api key to fetch the data. I honestly have no clue at all. It's my first time to work with apis and I feel sooo lost :((
If there are any API pros out there, I would greatly appreciate your assistance!
Thanks
UPDATE: I managed to add the api as a header while fetching the data in this format:
fetch(URL, {
headers: new Headers({
'API-KEY' : '[api-key-here]' })
})
However, I got this error in my browser: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.qoyod.com/api/2.0/invoices/1. (Reason: CORS request did not succeed)."
Does this mean I need to be granted access by the owner of the api server?
Try to run below code snippet. and make sure you have data in correct JSON Object format. Below i try to replicate the problem. assume you have data in data variable after Ajax call.
function displayData() {
const div = document.getElementById("result");
/* const URL = 'https://www.qoyod.com/api/2.0/invoices/1';
fetch(URL)
.then((resp) => resp.json())
.then(function(data)
{ */
let data = {
results: [{
"index": 1,
"code": "170"
},
{
"index": 2,
"code": "175"
}
]
};
let invoices = data.results;
invoices.map(function(invoice) {
let p = document.createElement('p');
p.innerHTML = `${invoice.index}`;
div.appendChild(p);
})
// })
/*
.catch(function(error) {
console.log(json.stringify(error));
})*/
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Qoyod Assignment</title>
<link href="styles.css" rel="stylesheet">
<script type="text/javascript" src="scripts.js"></script>
</head>
<body>
<div id="root">
<input style="float: left; margin-right: 10px;" type="text" placeholder="Enter API Key" />
<button onClick="displayData();">Display Data</button>
<div id="result"></div>
</body>
</html>
If you are use postman than its very easy to you. You need api key pass to header and they already provide what data pass in body.

why bindCallback is not a function?

Hi I am using this rxjs libraray .I am getting this error
Rx.Observable.bindCallback is not a function
here is my code
http://jsbin.com/tuxucotake/edit?html,js,console,output
I am reading doc from here
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html
var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
result.subscribe(x => console.log(x), e => console.error(e));
You are using RXJS 4 but the docs you have linked to are RXJS 5
Based on #Günter Zöchbauer answer, bindCallback() is not anymore part of Observableso the correct usage for current version of RxJs (6) would be:
jsbin
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<title>JS Bin</title>
</head>
<body>
</body>
</html>
js
var getJSONAsObservable = rxjs.bindCallback(jQuery.getJSON);
var result = getJSONAsObservable('https://mysafeinfo.com/api/data? list=englishmonarchs&format=json');
result.subscribe(
([data,textStatus,jqXhr]) => console.log(data),
e => console.error(e));
Respectively for node:
const Rx = require('rxjs')
const {bindCallback} = Rx;
var getJSONAsObservable = bindCallback(jQuery.getJSON);
....

Categories

Resources