Phillip Quy Le Phillip Quy Le - 1 year ago 214
JSON Question

Wikipedia API call is not returning results

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

var api = "|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=";

alert(api + userInput);

$.getJSON(api + userInput, function(wikiData) {

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

Answer Source

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

XMLHttpRequest cannot load…&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() {

    var api = "|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=mudit";

        type: 'GET',
        url: api,
        async: false,
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(data){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download