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" );
});
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));
}
});
});