I have an input box with button. When I enter an input, i want that input to be passed to a variable called 'town' that i can use in my fetch API call. When i try this, it says the variable is undefined. To test, i can get the Fetch API to work if i define the variable 'town' as 'garstang' e.g. var town ='garstang';
But i want to make 'town' get its input from the result of my input box, which is 'inputVal'.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="js.js"></script>
<title>Javascript Calling APIs</title>
</head>
<body>
<h1>Test</h1>
<p id="demo"></p>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="getInputValue();">Get Value</button>
<script>
function getInputValue() {
// Selecting the input element and get its value
var inputVal = document.getElementById("myInput").value;
// Displaying the value
alert(inputVal);
}
</script>
<script>
var myHeaders = new Headers();
myHeaders.append("x-rapidapi-key", "insert_key_here");
var town ='garstang';
// var town = inputVal;
var url = "https://wyre-data.p.rapidapi.com/restaurants/town";
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch(url + '/' + town, requestOptions)
.then(response => response.text())
// .then(result => console.log(result))
.then(result => document.getElementById("demo").innerHTML =
"<strong>The answer is: </strong>" + (result))
.catch(error => console.log('error', error));
</script>
<h2>The End...</h2>
</body>
</html>
