Please bear with me, i'm very new to coding.
I've loaded two images from an API (randomPrint1 and randomPrint2), but they both display at the same time. How do I preload these images successfully and display them in the draw function when I want to?
Ideally, I'd have a different image (from the API) display each time I click on the page. I want to be able to format the display of the page in javascript too if that's possible.
Thanks! Here's the code I have so far in js and html:
js:
randomPrint1 = ["https://api.harvardartmuseums.org/object?apikey=f26d41e3-69ac-4735-9027-0d4607177a6a&size=1&page=512"];
randomPrint2 = ["https://api.harvardartmuseums.org/object?apikey=f26d41e3-69ac-4735-9027-0d4607177a6a&size=1&page=2115"];
const random = Math.floor(Math.random() * [randomPrint1, randomPrint2].length);
//console.log(random, randomPrint1[random]);
let baseimageurl;
let img = [randomPrint1[0,1], randomPrint2[0,1]];
function preload(){}
fetch(randomPrint1)
.then(res => res.json())
.then(res => console.log("success!", res))
.catch(err => console.log("something went wrong...", err));
fetch(randomPrint1)
.then(response => response.json())
.then(response => {
//console.log(response)
resPrints = response
let randomPrint1 = document.querySelector("#randomPrint1")
for(i=0; i<resPrints.records.length; i++){
//console.log(resPrints)
let printsElement = document.createElement("img")
if (resPrints.records[i].images.length>0){
printsElement.setAttribute("src", resPrints.records[i].images[0].baseimageurl)
printsElement.setAttribute("width", 290)
printsElement.setAttribute("height", 200)
randomPrint1.appendChild(printsElement)}
}
})
fetch(randomPrint2)
.then(res => res.json())
.then(res => console.log("success!", res))
.catch(err => console.log("something went wrong...", err));
fetch(randomPrint2)
.then(response => response.json())
.then(response => {
//console.log(response)
resPrints = response
let randomPrint2 = document.querySelector("#randomPrint1")
for(i=0; i<resPrints.records.length; i++){
//console.log(resPrints)
let printsElement = document.createElement("img")
if (resPrints.records[i].images.length>0){
printsElement.setAttribute("src", resPrints.records[i].images[0].baseimageurl)
printsElement.setAttribute("width", 290)
printsElement.setAttribute("height", 200)
randomPrint2.appendChild(printsElement)
}
}
})
function setup(){
createCanvas(400, 400);
background(200);
}
function draw(){
}
html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<header>
</header>
<Main>
</Main>
<footer>
</footer>
<div id="randomPrint1">
</div>
<div id="randomPrint2">
</div>
<script src="sketch.js"></script>
</body>
</html>
I've moved the 'fetch' around, and tried to toggle the display of the URLs. Tried to treat the URLs as an image and load them in the draw function. No luck.
Related
I am trying to upload an mp3 from my computer into a soundtouch audio context in order to change the tempo and pitch.
HTML
<form class="form" id="form">
<input type="file" id="inputFile"><br>
<button type="submit">Upload File</button>
</form>
JavaScript:
const myForm = document.getElementById("form");
const inputFile = document.getElementById("inputFile");
myForm.addEventListener("submit", e => {
e.preventDefault();
const data = new FormData();
data.append("inputFile", inputFile.files[0]);
playBtn.setAttribute('disabled', 'disabled');
if (shifter) {
shifter.off();
}
fetch(data)
.then((response) => response.arrayBuffer())
.then((buffer) => {
audioCtx.decodeAudioData(buffer, (audioBuffer) => {
shifter = new PitchShifter(audioCtx, audioBuffer, 16384);
shifter.tempo = speedSlider.value;
shifter.pitch = pitchSlider.value;
shifter.on('play', (detail) => {
currTime.innerHTML = detail.formattedTimePlayed;
progressMeter.value = detail.percentagePlayed;
});
duration.innerHTML = shifter.formattedDuration;
playBtn.removeAttribute('disabled');
});
});
})
When I try this code, I get two error messages:
GET ...(port number)... 404 (NOT FOUND)
100.64.5.65/:1 Uncaught (in promise) DOMException: Unable to decode audio data
Any help would be appreciated as I don't know how to fix this.
code screenshot
I am getting undefined when I type the author name in the text box and press the button to display the quote. It seems like my button and textbox are not linked together. How can I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Quotes</title>
</head>
<body>
<label for="getQuotes">Find Quotes (Type Author Name)</label><br>
<input type = "text" id="getQuotes" name="getQuotes" placeholder="Search" style="margin:10px" size="50"/><br />
<button id="FetchQuotes" onclick="getQuote()" style="margin:10px">Fetch Quotes</button>
<p id="quotes"></p>
<p id="author"></p>
<script>
async function getQuote() {
//const author = Boolean(false);
let url = 'https://jaw1042-motivate.azurewebsites.net/quote';
let author = document.getElementById('getQuotes').value;
if(author) {
url = 'https://jaw1042-motivate.azurewebsites.net/quote?author= ';
console.log(url + author);
} else {
console.log(url);
}
fetch(url)
.then(async (response) => {
if (response.ok) {
console.log("Response code: " + response.status);
} else if (response.status === 400) {
console.log("Unable to find any quotes by specified author: " + response.status);
} else {
console.log("No quotes have been loaded: " + response.status);
}
const val = await response.json();
console.log(val);
}).then(data => {
document.getElementById('quotes').value = data;
document.getElementById('author').value = data;
console.log(data);
alert(data);
});
}
</script>
</body>
</html>
your then functions are not correct
in the direct result of the fetchAPI you can receive data and to use it you need to run .json() or .text() on it, you can't simply use that result or return it's value ( plus when you use return statement all your next codes will be unreachable)
after that you should not assign something to your data variable because it just has new Data fetched from backend, by assigning new value to data you're about to ruin new data
here is how your js should look
function getQuote() {
fetch("https://krv1022-motivate.azurewebsites.net/quote")
.then( res => res.text() )
.then( data => {
document.querySelector(".quote").value = data;
}
);
}
I also provided a fiddle for it but it can't receive data because either your URL is not correct or there is CORS issues
==============================================
one thing that I just noticed, you are receiving Author's name from end user but you are not about to send it to backend!
so perhaps this code is more complete, I assume that you want to send data using GET method and backend wants the name of author to be named getQuotes
How can I put my API get's return value onto an html page?
If I do:
const url = "https://alloysystems.freshdesk.com/api/v2/tickets";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"authorization": "Basic ILLNEVERGIVEYOUMYKEYKEYLOL"
}
})
.then(resp => resp.json())
.then(data => console.log(data))
I get a bunch of objects, (I think) in the console log:
However if I try to add the data to html tag so I can see it on a webpage, I either get a failure or I get [Object],[Object]
Attempted code:
Html:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Today's Date</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<script src="js/script.js"></script>
</body>
</html>
Javascript:
let d = new Date();
const url = "https://alloysystems.freshdesk.com/api/v2/tickets";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"authorization": "Basic ILLNEVERGIVEYOUMYKEYKEYLOL"
}
})
.then(resp => resp.json())
.then(data => document.body.innerHTML = "<h1>" + data + "</h1>")
Result:
data is an object so if you want to show everything of it between the h1 tag you need to stringify it first like so :
.then(data => document.body.innerHTML = "<h1>" + JSON.stringify(data) + "</h1>")
If you just want to show the type for example you need to specify that part like so:
.then(data => document.body.innerHTML = "<h1>" + data.type + "</h1>")
You need to convert it from an Object to JSON using
JSON.stringify(value, replacer, space)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
If you want to show it formatted (multiline and indented) on the html page, put in inside a <pre> tag.
See example below in the snippet
fetch(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=2&page=1`
)
.then((r) => r.json())
.then((d) => {
const pre = document.createElement('pre');
pre.innerText = JSON.stringify(d, null, `\t`)
document.querySelector('body').appendChild(pre);
});
body,
pre {
color: white;
background: #0080ff;
font-family: Calibri
}
idk what I did with my code, but yesterday this fetch was working. I extract a kitty pic from API.
Today when i tried its not working, it says that url is not defined. Same problem have my friend from bootcamp. Something happens with a API.
function getKitties() {
fetch("https://api.thecatapi.com/v1/images/search")
.then((response) => {
(response.json())
.then((response) => {
(console.log(response)
)
})
var cat = response[0].url;
})
var imgcat = document.createElement("img");
imgcat.src = cat;
var dtag = document.createAttribute("data-tag");
dtag.value = "img-kitty";
imgcat.setAttributeNode(dtag);
imgcat.innerHTML = " "
document.body.appendChild(imgcat);
}
<button id="searchKitty" onclick="getKitties()">Click me</button>
You need to move the action into the THEN
Here is a version that is using recommended methods, addEventListener and catch and also a simplified data attribute
document.getElementById('searchKitty').addEventListener('click', e => {
fetch('https://api.thecatapi.com/v1/images/search')
.then(response => response.json())
.then(response => {
console.log(response);
var cat = response[0].url;
var imgcat = document.createElement("img");
imgcat.src = cat;
imgcat.dataset.tag = "img-kitty";
imgcat.setAttribute("alt",response[0].breeds.join("") || "Cat")
document.body.appendChild(imgcat)
})
.catch(error => console.log(error.message));
})
img {
height: 100px;
margin: 5px;
}
<button id="searchKitty" type="button">Click me</button>
<hr/>
With a QR code vcard, the user scans the code with their phone and then the dialog with the "add to contacts" pops up on their phone, such as the code below:
How can I do the same but instead of a QR code scan, I want it to do the same with a button click.
I have tried the following:
var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, loadvcard);
function loadvcard(){
url = "BEGIN%3AVCARD%0AVERSION%3A3.0%0AN%3ADoe%3BJohn%0AFN%3AJohn%20Doe%0ATITLE%3A08002221111%0AORG%3AStackflowover%0AEMAIL%3BTYPE%3DINTERNET%3Ajohndoe%40gmail.com%0AEND%3AVCARD";
window.open(url);
}
You can open your vcard in the browser as a data url if you want.
Your code would be:
var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, loadvcard);
function loadvcard(){
var data = "BEGIN%3AVCARD%0AVERSION%3A3.0%0AN%3ADoe%3BJohn%0AFN%3AJohn%20Doe%0ATITLE%3A08002221111%0AORG%3AStackflowover%0AEMAIL%3BTYPE%3DINTERNET%3Ajohndoe%40gmail.com%0AEND%3AVCARD";
window.open("data:text/x-vcard;urlencoded," + data);
}
Try to use the web share api, it works.
<html>
<title>
Web Share API
</title>
<body>
<div>
<div>
<button onclick="shareVcard" id="shareFilesButton">Share Files</button>
</div>
</div>
</body>
<script>
document.getElementById('shareFilesButton').addEventListener("click", () => shareVcard())
function shareVcard() {
fetch("sample.vcf")
.then(function(response) {
return response.text()
})
.then(function(text) {
var file = new File([text], "sample.vcf", {type: 'text/vcard'});
var filesArray = [file];
var shareData = { files: filesArray };
if (navigator.canShare && navigator.canShare(shareData)) {
// Adding title afterwards as navigator.canShare just
// takes files as input
shareData.title = "vcard";
navigator.share(shareData)
.then(() => console.log('Share was successful.'))
.catch((error) => console.log('Sharing failed', error));
} else {
console.log("Your system doesn't support sharing files.");
}
});
}
</script>
</html>