How do I get a user input and insert it into the api link is JavaScript? [closed]

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=320, initial-scale=1">
<meta charset="utf-8">
<style>
  body, html {
    min-width: 100%;
    min-height: 100%;
    margin: 0;
    padding: 0;
    font: Arial 14px;
  }
</style>
</head>
<body>
<p>
  Enter GD Username:
</p>
<input id="bruh">
<script>      
  var bruh = document.getElementById("bruh").value;
  const url = `https://example.com/api/${bruh}`;
  async function getData() {
  const response = await fetch(url);
  const data = await response.json();
  console.log(data);
}
</script>
<button onclick="getData()">
Try
</button>
</body>
</html>

Hey guys, right now I’m trying hard to make a system that can fetch data from an api from what the user types in. What I have done already is make the fetching work, and the variable works, but for some reason when I type in something in the input box, it doesn’t work. Anyone know why?

Answer

The problem is you click the button the bruh variable is already declared but not defined. so You need to have these 2 lines inside your function:

var bruh = document.getElementById("bruh").value;   
const url = `https://example.com/api/${bruh}`;

So you final code should look like this:

<script>      
  
async function getData() {
  var bruh = document.getElementById("bruh").value;
  const url = `https://example.com/api/${bruh}`;
  const response = await fetch(url);
  const data = await response.json();
  console.log(data);
}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *