you are calling your getGif() function before the form was submitted. The event listener is not a synchronous event. To fix this, you can just move it into the event listener block:
let searchInput = document.getElementById("searchInput");
document.querySelector("form.gform").addEventListener("submit", function (e) {
e.preventDefault();
console.log(searchInput.value);
getGif(); // move it up here. now it will work.
});
let randomIndex = Math.floor(Math.random() * 10);
async function getGif() {
const res = await axios.get("https://api.giphy.com/v1/gifs/search", {
params: {
api_key: "tGZu4GXgLVVp0VTINvh66xcmIfJBPqoP",
q: searchInput,
},
});
console.log(res.data.data[randomIndex].url);
}
I am working on a homework project where I need to create a search, I need to take that search and plug it into an API request peram and have that API come back with a Gif URL relating to that search. I have the code for the search event listener, and I have the code for the API get request, where I am coming into trouble is getting them to work together. When I comment out one piece of code out the stand-alone works as intended. I am trying to get the search URL to print to the console just to test to make sure I am receiving a URL. In the end, I will be appending it to the DOM but right now I am just focused on getting the URL back from the API.
Any input is appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Giphy Party!</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container text-center">
<h1>The Giphy Party!!!!!</h1>
<h2>It is Party Time!!!!!</h2>
</div>
<form class="gform">
<label for="search">
<input id="searchInput" type="text" />
</label>
<button>Search Gif</button>
<button>Remove Gifs</button>
</form>
<div class="container"><img id="img" src=""" alt="" /></div>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"
></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://unpkg.com/axios/dist/axios.js"></script>
<script src="app.js"></script>
</body>
</html>
'''let searchInput = document.getElementById("searchInput");
document.querySelector("form.gform").addEventListener("submit", function (e) {
e.preventDefault();
console.log(searchInput.value);
});
let randomIndex = Math.floor(Math.random() * 10);
async function getGif() {
const res = await axios.get("https://api.giphy.com/v1/gifs/search", {
params: {
api_key: "tGZu4GXgLVVp0VTINvh66xcmIfJBPqoP",
q: searchInput,
},
});
console.log(res.data.data[randomIndex].url);
}
getGif();'''