0

I'm trying to implement the Wikipedia Search API and write the results to the page. (They show up in the console.)

I've tried a for loop through "data.query.search.title". I tried "JSON.stringify(data, null, 2)" but that's not what I was looking for.

Here is a JSFiddle:

https://jsfiddle.net/magoo/s8t5qb3u/4/

'''function search(event) {

  event.preventDefault();

  var input = document.getElementById('searchInput'). value;
  var searchText = input.trim().toLowerCase();

var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=links&list=search&srsearch=" + searchText + "&srnamespace=0&srinfo=&srprop=snippet%7Ctitlesnippet&callback=?"
$.getJSON (url, function(data) {

var output = data.query.search;

display.innerHTML = output;
console.log(output);

})}

 '''

The console shows multiple objects. The page shows [Object object] repeated multiple times.

My hope is to get the title, snippet, and URL.

Hope I did this post correctly. Thanks in advance.

magoo
  • 3
  • 2

1 Answers1

0

The reason you see [Object object] is precisely because you're trying to output a complex object to the screen. Clearly you need to output the items within it. You can't just dump the whole object because JavaScript has no idea how you want it to appear.

output in your code is an array (we can see that from the console log). So you need to loop through the array, and for each entry, print the desired properties. The objects within the results don't seem to have a URL (as you mentioned) but they do have a title and snippet.

Demo (I also refactored your code a little to make it neater):

$("#searchButton").click(function() {
  search($("#searchInput").val());
});

function search(searchText) {

  var searchText = searchText.trim().toLowerCase();

  var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=links&list=search&srsearch=" + searchText + "&srnamespace=0&srinfo=&srprop=snippet%7Ctitlesnippet&callback=?"
  $.getJSON(url, function(data) {

    var output = data.query.search;

    for (i = 0; i < output.length; i++) {
      display.innerHTML += "<li>" + output[i].title + " - " + output[i].snippet + "</li>";
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Wikipedia Search</h1>
<input type="search" id="searchInput">
<br>
<input type="button" id="searchButton" value="Search">
<br>
<ul id="display"></ul>
ADyson
  • 57,178
  • 14
  • 51
  • 63