0

I am trying to use Stack Exchange's questions API in my JS file to display questions containing the search keyword on a webpage.

Here is my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>API Test</title>
  <link rel="stylesheet" href="indexStyles.css">
</head>
<body>
    <script src="main.js"></script>

    <input id="searchbar" type="text" name="search" placeholder="Search keywords...">
    <button onclick="getKeyword()"> Search </button>


    
</body>

</html>

Here is my JS code (file name: main.js):

let api_url = "https://api.stackexchange.com/2.3/questions?order=desc&sort=activity&site=stackoverflow"

function getKeyword() {

    fetch(api_url) 
    .then(response=>response.json())

    .then(data=>console.log(data))

    let inputKeyword = document.getElementById("searchbar").value
    document.write(inputKeyword) //printing keyword just to see if the function works
}

The button upon clicking displays the input keyword just as the function getKeyword() was tasked to do. However, I don't know how to fetch api_url. As you can see, I tried the fetch() method but I didn't get the intended output. I tried changing console.log(data) to document.write(data) and the latter prints HTML[object Object] on the webpage when the keyword entered in the search bar is HTML. Also, I didn't get any errors in my console when I ran the code. I'm new to JS so any help on this matter would be greatly appreciated! Refer to the API link if you'd like to see how the JSON data looks like.

Below are screenshots of my output:

Webpage upon running HTML file Webpage after searching keyword

  • Look at the structure of the data returned, and then figure out how you want to iterate through it and display it onto the page - how you want to display it is up to you. For a lazy method just to see that things are working, you can use `JSON.stringify(data)` – CertainPerformance Sep 06 '21 at 20:56

0 Answers0