0

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

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • you can use a combination of a form element for the user input and a JS function for handing the request to the API. In the JS function you can use fetch to make the request to the API. – Eugene Upston Jun 27 '20 at 11:38

3 Answers3

1
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}.

Nikhil Adiga
  • 150
  • 2
  • 9
0

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.

Allan Juan
  • 2,048
  • 1
  • 18
  • 42
0
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.