Issue with GIPHY API Implementation
I’m having trouble getting my GIF search feature to work properly. I’m pretty new to API integration and can’t figure out what’s going wrong with my code.
The main problem is that when users try to search for specific GIFs, nothing happens. I want to capture what the user types in the search box and use that to fetch relevant GIFs from GIPHY.
JavaScript Code:
document.addEventListener('DOMContentLoaded', function () {
const apiKey = 'dc6zaTOxFJmzC';
let searchTerm = 'dancing dog'; // hardcoded for testing
const xhr = new XMLHttpRequest();
xhr.open('GET', `http://api.giphy.com/v1/gifs/search?q=${searchTerm}&api_key=${apiKey}`);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
const response = JSON.parse(xhr.responseText);
const gifUrl = response.data.image_url;
console.log(gifUrl);
document.getElementById('gif_container').innerHTML = `<div><img src="${gifUrl}" alt="GIF from Giphy"></div>`;
} else {
console.log('API request failed with error');
}
};
xhr.onerror = function() {
console.log('Network connection failed');
};
xhr.send();
});
HTML Structure:
<h2>GIF Search Tool</h2>
<div class="search-container">
<p>Enter keywords to find awesome GIFs!</p>
<form class="search-form">
<input type="text" id="search-term" class="input-field">
<button type="submit" class="submit-btn">Find GIFs</button>
<input type="reset" value="Clear">
</form>
<div class="results-area">
<p id="gif_container"></p>
</div>
</div>
Can someone help me understand how to properly connect the user input to the API call?