Alby11
Alby11

Reputation: 645

Wikipedia AJAX call

I have this code, it does an AJAX call to Wikipedia, asking for results of a given query (var searchText):

function main() {
    $(".btn").click(function() {
        $("#iframe").attr('src', 'https://en.wikipedia.org/wiki/Special:Random');
        $(".embed-container").css('visibility', 'visible');
    });

    function wikiAjax (searchURL) {
        return $.ajax({
            url: searchURL,
            jsonp: "callback",
            dataType: 'jsonp',
            xhrFields: {
                withCredentials: true
            }
        });
    }

    $(".search-form").submit(function() {
        event.preventDefault(); 
        var searchText = $('#search').val();
        var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
        console.log(searchURL);
        var wikiResponse = wikiAjax(searchURL);
        wikiResponse.done(function(data) {
            console.log(data);
        }).fail(function(err) {
            alert("The call has been rejected");
        });
    });
}

$(document).ready(main);

But it returns me a strange object:

image

Could someone please help me?

Upvotes: 1

Views: 1231

Answers (3)

Jordan  Service
Jordan Service

Reputation: 1

This is the correct response for a query that has no matches. the issue is most likely the search value you are appending.

Below are two result sets, one using a term that yields no response the other using Test.

Response with no results: No Results

Response with results: Results

Upvotes: 0

Clomp
Clomp

Reputation: 3308

The Ajax call needs to have 3 parameters. There is JSON data in the 3rd param. Try it with this jsfiddle.

wikiResponse.done(function(error, success, data) {
    console.log(data.responseJSON.query.pages);
})

Upvotes: 0

Ahmed Ayoub
Ahmed Ayoub

Reputation: 794

you've the right response from Wikipedia, check your query parameters, specially this one

var searchText = $('#search').val();

which value you are testing with, if you entered something like "2sasd23sda" you'll get this object response.

Upvotes: 2

Related Questions