Giphy API search query returns no results despite user input

I’m working on a web app that connects to the Giphy API but running into an issue. When users type something into the search box and click submit, the API call returns empty results. I checked the browser console and it shows that the search term is coming through as blank, even though there’s definitely text in the input field.

Here’s my JavaScript code:

let submitButton = $("#searchBtn");
let searchTerm = $("#searchBox")
  .val()
  .trim();
let titleElement = $("#mainTitle h1");
let apiKey = "YOUR_API_KEY_HERE";
let resultsArray = [];

$(submitButton).on("click", function() {
  event.preventDefault();
  let apiUrl =
    "https://api.giphy.com/v1/gifs/search?api_key=" +
    apiKey +
    "&limit=5&q=" +
    searchTerm;
    
  fetch(apiUrl)
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(data => {
      console.log(data);
      console.log(data.data);
    })
    .catch(error => console.log(error));
});

And the HTML structure:

<div id="searchContainer">
  <input
    type="search"
    placeholder="Find GIFs..."
    id="searchBox"
  />
  <input type="submit" value="Search" id="searchBtn" />
</div>
<script src="js/main.js"></script>

Any ideas why the search parameter isn’t getting passed to the API correctly?

You’re grabbing the search term value outside the click handler. When your script loads, searchTerm gets set to whatever’s in the input box right then - probably nothing. Later when someone types and clicks search, you’re still using that original empty value. Just move let searchTerm = $("#searchBox").val().trim(); inside your click handler, right after event.preventDefault();. Now it’ll grab the actual value when they click, not when the page loads. I hit this exact same bug building a search feature last year. It’s a timing mistake that trips up tons of developers.