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?