Search code examples
ajaxangularjsjsonpmediawiki

$http.jsonp for wikipedia doesnt work


I have a small project in jQuery that calls wikipedia API by jsonp technique. here is the snippet of codes in jQuery:

    // load wikipedia data
var wikiUrl = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' + cityStr + '&format=json&callback=wikiCallback';
var wikiRequestTimeout = setTimeout(function(){
    $wikiElem.text("failed to get wikipedia resources");
}, 8000);

$.ajax({
    url: wikiUrl,
    dataType: "jsonp",
    jsonp: "callback",
    success: function( response ) {
        var articleList = response[1];

        for (var i = 0; i < articleList.length; i++) {
            articleStr = articleList[i];
            var url = 'http://en.wikipedia.org/wiki/' + articleStr;
            $wikiElem.append('<li><a href="' + url + '">' + articleStr + '</a></li>');
        };

        clearTimeout(wikiRequestTimeout);
    }
});

I am trying to convert to $http.jsonp in AngularJS, and here is the snippet of codes that is trying to get a same result:

            var wikiUrl = appSettings.wiki + $scope.address.city + '&format=json&callback=wikiCallback';

        $http.jsonp(wikiUrl).success(function(res){
            console.log(res);

        }).error(function(){
            console.log('Wrong entry for Wikipedia!');
        });

but it cat get anything and I have the following error

Uncaught ReferenceError: wikiCallback is not defined

Please help.


Solution

  • Angular expects you to define JSONP callback function name as JSON_CALLBACK. So your code should be:

    var wikiUrl = appSettings.wiki + $scope.address.city + '&format=json&callback=JSON_CALLBACK';
    

    Reference: $http.jsonp.