Search code examples
javascriptjquerygetjsonwikipedia-apimediawiki-api

Wikipedia API Hello World not working?


The following simple code isn't working for Wikipedia API. I'm not sure why.

html:

<button id="main" onclick=doThis()>Main</button>
<div id="result">h<div>

Script:

function doThis() {
var wikiUrl = "https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json";
$.getJSON(wikiUrl, function(data) {
  alert(data);
}, 
  $('#result').html("no")
)}

Output: the $('#result').html("no") line gets executed which I believe means that the getJSON didn't return anything.

What's wrong & how do I fix this?


Solution

  • If you open the browser's console, you'll see this error:

    XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access.

    This indicates that you need to instruct $.getJSON() to use jsonp.

    To do so, simply add

    &callback=?
    

    to your url.

    But, as @Rory commented, note:

    Note that JSON and JSONP aren't directly interchangeable. This only works here as Wikipedia supports JSONP, whereas many API providers do not.

    So changing your code to

    function doThis() {
    
        var wikiUrl = "https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json&callback=?";
    
        $.getJSON(wikiUrl, function(data) {
            alert(data);
        }); 
    )}
    

    will work.

    Note that $('#result').html("no") is not a callback, so using it as one doesn't have any positive effect.