Trying to fetch and display image from api using javascript? - javascript

I am currently building a football website using LiveScore API to fetch data. Needless to say, I am actually learning API fetch using this project. This api fetch current day's fixture. I tried to get the two teams T1 and T2 with their name playing against each other in my HTML file. I got the output below.
Output and api
There are overall 81 arrays, and I want to display logo of the team which is in T1 and T2 array in Img section just before the team name. But only a placeholder is displaying. What am I doing wrong?
I wrote some HTML and JS to fetch the data.
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>Football Live Today</title>
</head>
<body>
<div>
<h2>Football Live Today</h2>
<h3>Today's Fixtures</h3>
<ul>
<li id="fixtures"></li>
</ul>
</div>
<script src="popup.js"></script>
</body>
</html>
JS
async function fetchData() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '********',
'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};
const res = await fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?Category=soccer&Date=20231801&Timezone=-7', options)
const record = await res.json()
console.log('record', record)
const indices = [0, 1, 4, 49, 50];
const filteredStages = record.Stages.filter((stage, index) => indices.includes(index));
document.getElementById("fixtures").innerHTML = filteredStages.map(item => `
<li>${item.Cnm} | ${item.Snm} | <img src="('${item.Events[0].T1[0].Img}">
${item.Events[0].T1[0].Nm} Vs <img src="${item.Events[0].T2[0].Img}">
${item.Events[0].T2[0].Nm}</li>`);
}
fetchData();

Related

Basic Fetch API listing only the template [duplicate]

This question already has answers here:
Template literals like 'some ${string}' or "some ${string}" are not working
(7 answers)
How can I do string interpolation in JavaScript?
(21 answers)
Closed 4 months ago.
I am attempting to fetch an API for the user names. but instead of listing names it lists {user.name} rather than the actual names.
How it should look like:
How it ends up looking:
The code:
<!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>Users</title>
</head>
<body>
<h2>Users:</h2>
<ul></ul>
<script>
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => {
return res.json();
})
.then(data => {
data.forEach(user => {
const markup = '<li>${user.name}</li>';
document.querySelector('ul').insertAdjacentHTML('beforeend', markup);
});
})
.catch(error => console.log(error));
</script>
</body>
</html>
What am I doing wrong?

How to build and display Consent Pane PLAID with PHP

i want to integrate PLAID system on my project based Laravel framework. Currently i'm developing on step to display Consent Pane PLAID from this doc PLAID LINK DOC. I'm using the javascript code. but i still failed to integrate it. here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Plaid</title>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
</head>
<body >
plaid
</body>
<script>
const handler = Plaid.create({
token: 'link-sandbox-xxx',
onSuccess: (public_token, metadata) => {
console.debug("onSuccess");
console.log('public_token: ' + public_token);
console.log('account ID: ' + metadata.account_id);
},
onLoad: () => {
console.debug("onLoad");
},
onExit: (err, metadata) => {
console.debug("onExit");
console.log('metadata ' + metadata);
},
onEvent: (eventName, metadata) => {
console.debug("onEvent");
},
receivedRedirectUri: "https://domainname.com/plaid",
});
handler.open();
</script>
</html>
Display error
POST https://sandbox.plaid.com/link/workflow/start 400 (Bad Request)
Error: oauth uri does not contain a valid oauth_state_id query parameter.
i already added new URL my API menu on PLAID Dashboard but still display this error.
Please help. How do i able to integrate that on my laravel?
The receivedRedirectUri should not be set when initializing Link for the first time. It is used when initializing Link for the second time, after returning from the OAuth redirect.

TypeError: cannot read properties of undefined reading '2'

I am losing my mind, respectfully.
I am currently coding an assignment for my studies. I have to call an API using the async fetch method in Javascript using the Svelte framework. This is what i have in my app.svelte.
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Sollicitatie Opdracht Volcano</title>
<link rel='icon' type='image/png' href='/favicon.png'>
<link rel='stylesheet' href='/global.css'>
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'>
import { onMount } from "svelte";
const searchAnime = async () => {
var response = await fetch('https://api.jikan.moe/v4/anime?q=jujutsu', {
method: 'GET'
});
var result = await response.json();
return result;
}
let aniSearchPromise = searchAnime();
</script>
<h1>API Fetching System</h1>
<main>
{#await aniSearchPromise}
<h2>Laden. . .</h2>
{:then data}
<h2>{data.results[0]}</h2>
{:catch err}
<h2>Error while loading data.</h2>
{/await}
</main>
<svelte:head>
<title>aniAPI Test App</title>
</svelte:head>
<style>
main {
background-color: lavenderblush;
font-size: 15px;
}
h1 {
font-size: 25px;
}
</style>
I am getting an error at data.results[0] I have no clue how to fix this as I can see that the promise is listed as fulfilled. On data.results[data[2]] is all the fetched data. See screenshot below
Would anyone be able to explain what is happening and why it is undefined? Many thanks.
data.Results is not an array and and by seeing your object, probably data.Results does not exist here. In your object, data is an array so it should be used like data[2].
It seems that data has no attribute called results in your screenshot. Can't you just call data[0] or data[2] ?
Api works correctly, probably you are trying to get data before it fetches
var response = fetch('https://api.jikan.moe/v4/anime?q=jujutsu', {
method: 'GET'
}).then(response => response.json())
.then(result => {
console.log('Data [0] result', result.data[0]);
})

Is there a specific way to route to different pages on a GitHub Pages site?

I have a GitHub Pages site hosted here. The splash page to open displays just fine, but once you click in the circle to transition to the next page, landing.html, you are met with a 404 error. I have tried every possible way I can think of to fix this; Absolute references, local references, completely rearranging my whole file organization system, and nothing is working.
Here is my index.html file:
<!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>Portfolio</title>
<link rel="stylesheet" type="text/css" href="./css/title.css"></link>
</head>
<body>
<div class="container">
<div class="x-shape" id="x-left"></div>
<div class="x-shape" id="x-right"></div>
<div class="ripple" hidden="true"></div>
<div class="white-line" id="line-ver"></div>
<div class="white-line" id="line-hor"></div>
</div>
<div class="title">AVRIE LATTA</div>
<script src="jquery-3.6.0.js"></script>
<script type="text/javascript" src="js/title.js"></script>
</body>
</html>
Here is my title.js file:
const openLanding = () => {
window.location.href = "/html/landing.html";
};
const closeTitle = () => {
$(".container").animate({
width: `${$(".container").width() * 0.1}`,
height: `${$(".container").height() * 0.1}`
}, 750, () => {
$(".container").animate({
width: `${$(".container").width() * 1000}`,
height: `${$(".container").height() * 1000}`
}, 1000, () => {
$(".container").animate({
opacity: "-=1"
}, 1000, () => {
$(".title").animate({
opacity: "-=1"
}, 1000, () => {
$(".title").animate({
width: '5%'
}, 1000, openLanding());
});
});
});
});
};
$('.container').click(() => {
closeTitle();
});
My files are organized as follows:
site
index.html
html
landing.html
js
title.js
See: https://docs.github.com/en/pages/getting-started-with-github-pages/about-github-pages#types-of-github-pages-sites
In your case, you are hosting a page from the repository webdevportfolio. This would be a 'project' site. This means that the files in that repository start from the root page https://avrielatta.github.io/webdevportfolio/
In your js/title.js file, you have the following line:
window.location.href = "/html/landing.html";
This navigates to https://avrielatta.github.io/html/landing.html
Thus, GitHub Pages is tries to find a landing.html in a html repository, or html/landing.html in your 'user' site repository avrielatta.github.io.
To access the proper files/pages from your webdevportfolio repository, you can do something like:
// relative location
window.location.href = "html/landing.html";
// direct location
window.location.href = "/webdevportfolio/html/landing.html";

displaying api response on html page

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSON Test</title>
</head>
<body>
<h1>Hello World</h1>
<div id="myData"></div>
<script>
fetch('http://localhost:3000/api/product/1234567')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
console.log(data)
var mainContainer = document.getElementById("myData");
for (let key in data) {
var div = document.createElement("div");
div.innerHTML = 'name: ' + data[key] + 'label' + data[key];
mainContainer.appendChild(div);
}
}
</script>
</body>
</html>
Trying to fetch the json response and display it on html page. It's giving me an error: SyntaxError: Unexpected end of JSON input. I guess I'm here to maybe get some help on how to fix this and why this is happening. Thank you.
edit:
The response I get on my console :
{
product: 1234567,
name: 'TV',
salePrice: 149.99
}
The major reason is your response is not in the JSON format, which could be because of getting some non-json format response. Please post the sample JSON response format to understand better.

Categories

Resources