Reputation: 41
Ok so i am using https://nyaaapi.herokuapp.com/ to fetch the info
to fetch an anime you use https://nyaaapi.herokuapp.com/nyaa/anime?query={nameofanime}
i want to take the name of anime as user-input
i am relatively new to apis and json and i always used random endpoint. I wrote some js but it wasn't remotely correct
const userInput = document.querySelector("#userInput").value;
fetch("https://nyaaapi.herokuapp.com/nyaa/anime?query=${userInput}")
.then((response) => response.json())
.then((quote) => console.log(quote));
<html>
<head>
<title>
anime
</title>
</head>
<body>
<p>
Anime: <input id="userInput" value="{naruto}" />
<br />
<button id="submit">submit</button>
</p>
<script src="index.js"></script>
</body>
</html>
What is currently working : it is sending a request to the api and logging it!
What is currently not working : while it is sending a request and logging it. I cannot see the relevant information (picture below)
edit: the third answer is the most useful to my need. I will try to figure out how to show the logged info to the user now
Upvotes: 0
Views: 2236
Reputation: 545
You can do something like this, it will log to the console the result of the api call when the input gets submitted:
You need an input in your html:
<input id="input" type="text" />
And in your js:
function refreshData(e) {
const nameOfAnime = e.target.value;
const url = `https://nyaaapi.herokuapp.com/nyaa/anime?query=${nameOfAnime}`;
fetch(url)
.then((res) => res.json())
.then(console.log);
}
const input = document.getElementById("input");
input.addEventListener("change", refreshData);
Upvotes: 2
Reputation: 54
you can try this way
access the DOM element value using document.querySelector();
const userInput = document.querySelector("#userInput").value;
now use fetch()
function to make api request.
fetch((`https://nyaaapi.herokuapp.com/nyaa/anime?query=${userInput}`).then((data)=>{
console.log(data);
})
Upvotes: 0
Reputation: 93
I have worked on something similar before. This could give you a start.
window.onload=function(){
const input = document.getElementById("input");
const getName = document.getElementById("getName");
getName.addEventListener("submit", e =>{
// Prevent the form from submission
e.preventDefault();
// Get city name and store it in local storage
var inputVal = getName.value;
var api_url = "{apiurl}" + inputVal;
// Get the dataset
function refreshData() {
fetch(api_url).then(response =>{
response.json().then(json => {
let dataset = json;
let output = formatResponse(dataset);
})
// Catch error - for example, the user doesn't input a valid name
.catch(error => console.log("not ok")); // TO BE IMPROVED
})
};
});
};
<form id="getName" class="search">
<input type="text" id="input">
<button id="submit" type="submit">Search</button>
</form>
Upvotes: -1