fbliss fbliss - 3 months ago 8
HTML Question

How to dynamically append data to a webpage after API call?

I am trying to create a webpage that, given a user input, returns a list of results from wikipedia. I have gotten the call to Wikipedia's API to work fine, but when I attempt to append the data to my webpage, it flickers on for a split second and then disappears. I suspect it has to do with the event handlers, but I have tried several alternatives without luck. I also looked around SO and the web at large but could not find a solution. Here is my code:

var results = [];

$("#search").on("keydown", "#searchinput", function(event) {
if (event.key === "Enter") {
var searchParameter = encodeURIComponent(this.value);
var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";

$.getJSON(link, function(data) {
for (var key in data) {
results.push(data[key]);
}
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < results[i].length; j++) {
$("#results").append(results[i][j]);
}
}
})
}
});


Thanks in advance for any assistance you can provide! I am happy to provide more information if necessary.

Answer

The call to $.getJSON should be in the if block with the variable assignments.

var results = [];

$("#search").on("keydown", "#searchinput", function(event) {
  if (event.key === "Enter") {
    var searchParameter = encodeURIComponent(this.value);
    var link = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchParameter + "&limit=10&namespace=0&format=json&origin=*";

    $.getJSON(link, function(data) {
      for (var key in data) {
        results.push(data[key]);
      }
      for (var i = 0; i < results.length; i++) {
        for (var j = 0; j < results[i].length; j++) {
          $("#results").append(results[i][j]);
        }
      }
    })
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="search">
  <input id="searchinput" type="text">
</div>
<div id="results">

</div>