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/>
Related
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.
async function apiFetch() {
let response = await fetch("https://dog.ceo/api/breeds/image/random");
let success = await response.json();
const img = document.createElement("img");
img.src = success.message;
div.append(img)
}
then console is telling both fullfiled and pending when called function in console apiFetch()
From your sniff code, I guess you want to get the image URL and display into HTML.
I made two separate functions and on click event function.
First (getImageUrl()) is to get image URL.
Second (loadImage()) is to display image into HTML.
Last (updateImage()) is combine and call sequentially.
This demo will works.
<!DOCTYPE html>
<html>
<head>
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h2>Dog picture</h2>
<button onclick="updateImage()">Update Image</button>
<dev id="container"></dev>
<script>
async function getImageUrl() {
const response = await fetch("https://dog.ceo/api/breeds/image/random");
const data = await response.json();
return data.message;
}
async function loadImage(url) {
const options = {
method: "GET",
};
let response = await fetch(url, options);
if (response.status === 200) {
const imageBlob = await response.blob();
const imageObjectURL = URL.createObjectURL(imageBlob);
const image = document.createElement("img");
image.src = imageObjectURL;
const container = document.getElementById("container");
// remove existing image
while (container.firstChild) {
container.removeChild(container.firstChild);
}
// update image
container.append(image);
} else {
console.log("HTTP-Error: " + response.status);
}
}
async function updateImage() {
getImageUrl().then((imageURL) => {
loadImage(imageURL);
});
}
</script>
</body>
</html>
Result
References
Downloading images with node.js
How to Use Fetch with async/await
How do I clear the content of a div using JavaScript?
The onclick Event
Fetch image from API
I have the code below, completely new to programming and JavaScript. I need to merge the code, together, i.e. have 1 $(document).ready(function () please advise how to merge/organise code together in 1 file, so all logic carries out its jobs?
//Hide show the sub-cat field
$(document).ready(function () {
//Set field visibility for category
$("#test_category").change(SetFieldsVisibility);
$("#test_category").change();
});
function SetFieldsVisibility() {
var selectedValue = $("#test_category").val();
if (selectedValue === "") {
$("#test_subcategory").closest("tr").hide();
//$("#test_subcategory_name").attr("value","");
$("#test_subcategory_name").val("");
//$("#test_subcategory").attr("value","");
$("#test_subcategory").val("");
$("#test_subcategory_entityname").attr("value", "subcategory");
}
else {
$("#test_subcategory").closest("tr").show();
//$("#test_subcategory_name").attr("value","");
$("#test_subcategory_name").val("");
//$("#test_subcategory").attr("value","");
$("#test_subcategory").val("");
//$("#test_subcategory_entityname").attr("value","");
$("#test_subcategory_entityname").val("");
}
}
//MERGE BELOW CODE WITH TOP
$(document).ready(function () {
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
function selectdepartmentonChange() {
let primaryValue = $("#test_category option:selected").val();
let departmentValue = $("#test_selectdepartment option:selected").val();
if (departmentValue != null) {
primaryValue = departmentValue;
}
setSubCategory(primaryValue);
}
function onPrimaryChange() {
// get id of selected primary field
// this will work only if you render primary field as dropdown
let primaryValue = $("#test_category option:selected").val();
if (primaryValue == "281a04bf-84f4-eb11-94ef-000d3adae0c8" || primaryValue == "3ad4e7db-4533-ec11-b6e6-0022489a108f" || primaryValue == "7b7e1b08-62f4-eb11-94ef-000d3adae0c8") {
$("#test_selectdepartment").empty();
$("#test_selectdepartment").show();
$("#test_selectdepartment_label").show();
//get department category drop down
const query = "/fetchxml-subcategory-portal-lookup/?id=" + primaryValue;
fetch(query, {
method: "GET"
})
.then(response => response.json())
.then(data =>
Object(data.results)
.forEach(item => {
let option = document.createElement("option");
option.value = item.categoryid;
option.innerText = item.title;
$("#test_selectdepartment").append(option);
}))
.catch((error) => {
console.error('Error:', error);
});
// let the control load, then set....
setTimeout(function () {
let departmentValue = $("#test_selectdepartment option:selected").val();
if (departmentValue != null) primaryValue = departmentValue;
setSubCategory(primaryValue);
}, 500);
} else {
$("#test_selectdepartment").hide();
$("#test_selectdepartment_label").hide();
$("#test_selectdepartment").empty();
setSubCategory(primaryValue);
}
}
function setSubCategory(primaryValue) {
// remove all option from dependent field
$("#test_subcategory").empty();
const query = "/fetchxml-subcategory-portal-lookup/?id=" + primaryValue;
fetch(query, {
method: "GET"
})
.then(response => response.json())
.then(data =>
Object(data.results)
.forEach(item => {
let option = document.createElement("option");
option.value = item.categoryid;
option.innerText = item.title;
$("#test_subcategory").append(option);
}))
.catch((error) => {
console.error('Error:', error);
});
}
Sure. Just cut and paste your code from the second $(document).ready call into the first call.
$(document).ready(function () {
// First call:
// Set field visibility for category
$("#test_category").change(SetFieldsVisibility);
$("#test_category").change();
// Second call:
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
// the rest of your code stays down here
You can just put all the code into one function like this.
$(document).ready(function () {
//Hide show the sub-cat field
$("#test_category").change(SetFieldsVisibility); //Set field visibility for category
$("#test_category").change();
// register onPrimaryChange function to run on change of dwc_primarycategorization field
$("#test_category").change(onPrimaryChange);
$("#test_category").change();
$("#test_selectdepartment").change(selectdepartmentonChange);
$("#test_selectdepartment").change();
});
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>
I made lastposter avatar for my forum system.
What I want : when user avatar img does not exist, change file type multiple times.
For example; if user_user1_avatar.png does not exist, change url to user_user1_avatar.jpg and again if that does not exist change to user_user1_avatar.gif and so forth.
I try this, but still get 404 error.
var imgz = document.getElementsByClassName("lpavatar_forumID")[0];
function imageExists(url) {
return new Promise((resolve, reject) => {
const img = new Image(url);
img.onerror = reject;
img.onload = resolve;
const timer = setInterval(() => {
if (img.naturalWidth && img.naturalHeight) {
img.src = ''; /* stop loading */
clearInterval(timer);
resolve();
}
}, 10);
img.src = url;
});
}
imageExists("bburl/uploads/avatars/avatar_avatar1.png")
.then(() => imgz.src = 'bburl/uploads/avatars/avatar_avatar1.png')
.catch(() => imgz.src = 'bburl/uploads/avatars/avatar_avatar1.jpg')
.finally(() => imgz.src = 'bburl/uploads/avatars/avatar_avatar1.gif')
});
<img class="lpavatar_forumID" src="/avatar/user_user1.png" />
<img class="lpavatar_forumID" src="/avatar/user_user1.png" />
<img class="lpavatar_forumID" src="/avatar/user_user1.png" />