Daniel
Daniel

Reputation: 549

Can't get Wikipedia's API to work

I want to use Wikipedia's API to append search results to my page, but when I press enter, nothing shows up. Here's my code so far:

var apiURL = "https://en.wikipedia.org/w/api.php?callback=?";
$("input").on("keydown",function search(e) {
 if(e.keyCode == 13) {

    $("#display-result").empty();
    $.getJSON(apiURL, {
    action: 'query',
    format: 'json',
    inprop: "url",
    formatversion: 2,
    generator: 'search',
    gsrsearch: $("input").val(),
    gsrwhat: "text",
    prop: 'extracts|info',
    exsentences: 3,
    exintro: "",
    explaintext: "",        
    exlimit: 20,
  })

  .success(function(response) {
    response.query.pages.forEach(function(resp) {
      $('#display-result').append(
        "<a href='" + resp.fullurl + "' target= '_blank'><div id='result' class='results'><h3>" + resp.title + "</h3><p = class='extract'>" + resp.extract + "</p></div>");
    });
  });
 };
});

Here's a jsfiddle: https://jsfiddle.net/9j6v1Leo/

Upvotes: 2

Views: 80

Answers (1)

Pascalco
Pascalco

Reputation: 2826

Two things I noticed while looking at your jsfiddle:

  • You are using jquery functions but you don't include the jquery library.
  • Put your code inside $(document).ready(function() { }. With this you make sure that the DOM is ready for JavaScript code.

Here is a working jsfiddle: https://jsfiddle.net/v27a0964/

Upvotes: 1

Related Questions