Reputation: 29
I want to take an input value from the user and send it to an API. Basically, the API link takes the input in it.
http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC
Here q
, 'funny cat', is actually the user input. I want to make it dynamic.
In the search bar when users type a name, I want this value to be sent to the API and fetch the result to my page.
Link to my code files: Github project
Upvotes: 0
Views: 7289
Reputation: 29
http://api.giphy.com/v1/gifs/search?q=funny+cat&api_key=dc6zaTOxFJmzC
I had already connected the API to my web app. With a small change in the URL, I was able to solve my problem and this is how I did it.
http://api.giphy.com/v1/gifs/search?q=**"+ input +"**&api_key=dc6zaTOxFJmzC
Here 'input' is the user-input that's being fetched using DOM.
Upvotes: 0
Reputation: 150
let searchText = document.getElementByID('searchText').value;
let searchBtn = document.getElementByID('searchBtn').addEventListener('click',search());
async function search(){
let results = await axios.get(`http://api.giphy.com/v1/gifs/search?q=${searchText}/&api_key=dc6zaTOxFJmzC`)
console.log(results);
}
Give an ID of searchText to your input field and grab the values and store it in a variable. Add a click event listener to your search button and call the search function and used template literals to pass the value in your searchText variable in your URL string. ${your_variable}
.
Upvotes: 1
Reputation: 2558
There are several ways to fetch data from an API. One of them is using the fetch method.
async function fetchData(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}
To pass user input to the request, all you have to do is build the url string dynamically using string concatenation.
Upvotes: 0