Two buttons for one script JS in web - javascript

I want to put a button/a for each record and run script for that concrete record but i stuck.
Button/a:
<a class="record-delete" data-doc="<%= shop._id %>">
<img src="/trashcan.svg" alt="delete icon" />
</a>
Script:
const trashcan = document.querySelector('a.record-delete');
trashcan.addEventListener('click', (e) => {
const endpoint = `/shops/${trashcan.dataset.doc}`;
fetch(endpoint, {
method: 'DELETE'})
.then(response => response.json())
.then(data => window.location.href = data.redirect)
.catch(err => console.log(err));
});
Script works only for last record. I know that i can use:
document.querySelectorAll
Instead of:
document.querySelector
But I don't have any idea how to run script for concrete button/a, as it still need concrete variable/target.
Thank you in advance for help if You can ;)

maybe this will help, https://jsfiddle.net/px59m3t2/
const trashcans = [...document.querySelectorAll('a.record-delete')];
trashcans.forEach(trashcan => {
trashcan.addEventListener('click', (e) => {
alert(e.target.parentNode.getAttribute('data-doc'));
});
});

Related

Getting image from pokeapi

I am trying to display the image from pokeapi but I get an error when I input the name. When I input the number I do get the pokemon image after clicking twice. But when I search for another pokemon I get a number of the previous pokemon. I would appreciate the help on the proper way to display the image. Thanks.
Javascript:
HTML:
Display image:
I tried a few ways but cant seem to get it to work.
PokeAPI expects the input to be the name or ID of the Pokemon,try this code please
const pokemonInput = document.getElementById("pokemon-input");
const pokemonButton = document.getElementById("pokemon-button");
const pokemonImage = document.getElementById("pokemon-image");
pokemonButton.addEventListener("click", function() {
const pokemonName = pokemonInput.value.toLowerCase();
const apiUrl = `https://pokeapi.co/api/v2/pokemon/${pokemonName}/`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
const imageUrl = data.sprites.front_default;
pokemonImage.setAttribute("src", imageUrl);
})
.catch(error => {
console.error(error);
pokemonImage.setAttribute("src", "");
});
});

How to fetch filtered data in Javascript from rest-framework

I need to filter the generals using their team ID. But I cannot implement it.
my code:
In choose.js:
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.card-title').forEach(team => {
let team_id = parseInt(team.dataset.team)
console.log(team_id)
fetch(`/generals?team=${team_id}`)
.then((response) => response.json())
.then((result) => {
console.log(result)
})
});
})
In views.py:
class GeneralView(generics.ListAPIView):
queryset = General.objects.all()
serializer_class = GeneralSerializer
filter_backends = [DjangoFilterBackend]
filter_fields = ('team',)
In urls.py:
path('generals', views.GeneralView.as_view(), name='general_view')
In my browser console,. console.log(team_id) comes correctly but console.log(result) does not come correctly.
In one reload
In another reload
How to solve the problem?

What function is passed to cb here?

So I have a small project containing both frontend (html) and backend (express: server, routers) parts. The project isn't that clean, so the its main operationality is launched directly in html section. And not much is clear to me here, especially what function is passed to cb (callback) here?
I have the following code in part of my html page within js project:
const $ = document.getElementById.bind(document)
const request = (path, cb) =>
fetch(path)
.then((res) => {
if (res.ok) return res.json()
throw Error('HTTP error: ' + res.status)
})
.then(cb)
.catch((err) => ($('result').innerHTML = err))
const main = async () => {
const pinRequired = new URLSearchParams(document.location.search).get('pin')
const id = await request(`./qrcode?pin=${pinRequired}`, (json) => {
const { qrbase64, deeplink, pin, id } = json
$('qrcode').innerHTML = `<img src="${qrbase64}" alt="Red dot" />`
$('deeplink').innerHTML = ` ${deeplink.slice(0, 90)}...`
$('pin').innerHTML = pin ? pin : 'Not requested'
return id
})
setInterval(() => request(`./status?id=${id}`, ({ status }) => ($('result').innerHTML = status)), 1000)
}
main().catch(console.log)
Is this (json)? I also don't know why it is in () round brackets, however, it is an object, it cannot be passed as a callback, right?
And I also have a code in another file, which contains /qrcode route of my website. There is a function (quite big, so i'm not posting it, just pointing that it doesn't return function that may be passed as a callback).
If this callback 100% is in another part of the code, as you think, please let me know.
If what you're asking about is this callback (json) => { ... } in the code below:
request(`./qrcode?pin=${pinRequired}`, (json) => {
const { qrbase64, deeplink, pin, id } = json
$('qrcode').innerHTML = `<img src="${qrbase64}" alt="Red dot" />`
$('deeplink').innerHTML = ` ${deeplink.slice(0, 90)}...`
$('pin').innerHTML = pin ? pin : 'Not requested'
return id
});
Then this is what is known as an arrow function. You can read about them here on MDN. They are a shortcut syntax for declaring a function that also has a number of implementation differences.
Note, there are some other issues in your code as request() does not return a promise so it does no good to use await on it and you won't get the id back from return id either.
Also note that the request library has been deprecated and generally shouldn't be used for new code. There is a list of alternatives here, all of which support promises natively. My favorite in that list is the got() library.

Trouble using Fetch to grab a JSON value and output as text in html

I am trying to grab a value from an API and output it into my html code as text. The API link is "https://financialmodelingprep.com/api/v3/company/profile/AAPL" (data is in JSON). The code below is my attempt at getting the price. My end goal is to have the user enter a stock ticker into an input box and the price for the stock to be outputted as text. I have successfully used the document.value function for returning values upon button clicks but I am not able to get it to work using an API and fetch.
Thank you very much!
<!DOCTYPE html>
<html>
<head>
<title>Pareto</title>
<script>
function xStockPrice(); {
const fetch = require("node-fetch");
const apiURL = "https://financialmodelingprep.com/api/v3/company/profile/AAPL"
fetch(apiUrl)
.then((res) =>res.json())
.then(data => console.log(data.profile.price))
document.tickerInputForm.output.value=data.profile.price
}
</script>
</head>
<body>
<form name="tickerInputForm">
<input type="text" name="xTicker"/>
<input type="button" value="Get Quote" onclick="xStockPrice();"/>
<input type="text" name="output"/>
</form>
</body>
</html>
You just have a few minor errors in your code, it should look like this:
function xStockPrice(); {
const fetch = require("node-fetch");
const apiURL = "https://financialmodelingprep.com/api/v3/company/profile/AAPL"
// Before you used apiUrl, JavaScript variables are case sensitive
// so apiURL is not the same as apiUrl and vice versa
fetch(apiURL)
.then((res) => res.json())
.then(data => {
console.log(data.profile.price);
// Before this line lived outside of your then handler
// Which causes two issues:
// 1: data will be undefined, it only exists in the scope of this anonymous function
// 2: The code will execute before your request is finished, you use then to wait for the response, so even if you had created the variable data before, it would be undefined when this line was executed, you use then to fill in the value and then you can use it to set the value of your input element
document.tickerInputForm.output.value = data.profile.price;
})
.catch(error => console.log(error));
}
The error in your code is the semi-colon in your function declaration function xStockPrice();
It should be like this:
function xStockPrice(){
const fetch = require("node-fetch");
const apiURL = "https://financialmodelingprep.com/api/v3/company/profile/AAPL"
fetch(apiURL)
.then((res) => res.json())
.then(data => {
console.log(data.profile.price);
document.tickerInputForm.output.value = data.profile.price;
})
.catch(error => console.log(error));
}
Using the JavaScript fetch your code works fine.
<!DOCTYPE html>
<html>
<head>
<title>Pareto</title>
<script>
function xStockPrice() {
// const fetch = require("node-fetch");
const apiURL =
"https://financialmodelingprep.com/api/v3/company/profile/AAPL";
fetch(apiURL)
.then(res => res.json())
.then(data => {
console.log(data.profile.price);
document.tickerInputForm.output.value = data.profile.price;
})
.catch(error => console.log(error));
}
</script>
</head>
<body>
<form name="tickerInputForm">
<input type="text" name="xTicker" />
<input type="button" value="Get Quote" onclick="xStockPrice();" />
<input type="text" name="output" />
</form>
</body>
</html>

How could i implement Demographic Clarify.ai model on project built on react.js?

I've tried to build a simple React app using basic Clarifai.FACE_DETECT_MODEL, but now I wanna change it to more advanced "Demographic", maybe somebody knows how to di it?
I know that I have to change clarify model but idk exactly how to do it
onButtonClick = () =>{
this.setState({imageUrl: this.state.input});
app.modelsw
.predict(
Clarifai.FACE_DETECT_MODEL,
this.state.input)
.then(response =>this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log("OOOOOOPS fix me!!!!"));}````
the demographics now only support requests from the backend. This is the nodejs request.
const {ClarifaiStub} = require("clarifai-nodejs-grpc");
const grpc = require("#grpc/grpc-js");
const metadata = new grpc.Metadata();
metadata.set("authorization", "{My key}");
const stub = ClarifaiStub.json()
stub.PostWorkflowResults(
{
workflow_id: "Demographics",
inputs: [
{data: {image: {url: "https://static.independent.co.uk/s3fs-public/thumbnails/image/2015/06/06/15/Chris-Pratt.jpg"}}}
]
},
metadata,
(err, response) => {
if(response){
console.log(response.results[0].outputs[2].data.regions[0].data.concepts)
} else {
console.log(err)
}
}
)
I think you can replace
Clarifai.FACE_DETECT_MODEL with "c0c0ac362b03416da06ab3fa36fb58e3" to have it use the Demographics model.
I'm not sure if something like Clarifai.DEMOGRAPHICS will work (you can try if you want) but I believe that is just a variable holding the string representing the model. You could put a breakpoint in the debugging console of the web browser and examine the Clarifai object and look for a field that matches demographics in some way, and that is probably the variable for the hash.
Output from the call is specified here: https://www.clarifai.com/models/demographics-image-recognition-model-c0c0ac362b03416da06ab3fa36fb58e3#documentation
it should now be:
onButtonClick = () =>{
this.setState({imageUrl: this.state.input});
app.modelsw
.predict('c0c0ac362b03416da06ab3fa36fb58e3', this.state.input)
.then(response =>this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log('Oops fix me!'))
}

Categories

Resources