0

I've been playing around with APIs recently, and there is a bug that I don't know how to figure out yet.

Here is the JavaScript part:

var userInput = "";

$("#searchButton").click(function() {
  // get user input
  var userInput = $("#userInput").val(); 
  // clear input
  $('#userInput').val("");

  var api = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=";

  alert(api + userInput);

  $.getJSON(api + userInput, function(wikiData) { 
    alert("SUCCEEDED");
  });
});

Basically, when a user enters something and hit the search button, the alert("SUCCEEDED") does not show up, which means the API call did not go through. I tried calling different APIs (OpenWeatherMap API, famous quote API, etc.), and they worked just fine. It's just the Wikipedia API does not return results.

Update: When I added the code below after the API call, it returns "error."

  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });
bunbohue
  • 63
  • 6
  • 1
    Try using the browser debugging tools (in particular, the console window) to see if there are any errors. Try adding an error function. – jdigital Jun 22 '16 at 03:44

1 Answers1

-1

Check your browser's developer console while running your code. You will see this error:

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?format=json&action=query&generator=searc…&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=mudit. No 'Access-Control-Allow-Origin' header is present on the requested resource.

Solution: use jsonp. Here is an exampe:

$("#searchButton").click(function() {
    console.log('click');

    var api = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=mudit";


    $.ajax({
        type: 'GET',
        url: api,
        async: false,
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(data){
            console.log(JSON.stringify(data));
        }
    });
});
ordonezalex
  • 2,645
  • 1
  • 20
  • 33
Mudit
  • 69
  • 1
  • 11