Search code examples
javascriptjqueryjsonmediawiki-api

MediaWiki api JSON parsing error in javascript


I am accessing the media wiki api using javascript and returning a JSON, but when parsing/accessing the returned data and inserting the datastr variable into an existing div, I receive undefined. Here is my script code:

$.getJSON("http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images", function(data) {
    var datax = $.parseJSON(data);
    var datastr = datax.images[2];
    console.log(datastr); //prints nothing to the web console
});

The link itself is working appropriately I believe, returning a JSON: http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images

This may be a problem with either the way I am accessing the API, or just receiving/parsing the JSON.Ultimately, I need the image "001Bulbasaur.png". Thanks!

**Changing datax.images[2] to datax.parse.images[2] returns the same undefined.


Solution

  • Change

    var datastr = datax.images[2];
    

    To:

    var datastr = datax.parse.images[2];
    

    Update: Seems you are having cross-origin problems, its not making the request. This should work:

    $.ajax({
      dataType: "jsonp",
      url: "http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images",
      success: success
    });
    
    function success(datax){
        var datastr = datax.parse.images[2];
        console.log(datastr); //prints 001Bulbasaur.png 
    }
    

    Fiddle: http://jsfiddle.net/mRU3M/