'Use Ajax to Retrieve MediaWiki Full Image URL

MediaWiki has a url that directs to the full image url.

<img src=
      "https://www.mediawiki.org/wiki/Special:FilePath/Wikimedia_Hackathon_Prague_2019_-_Group_Photo_-_CLK_-_cropped.jpg"/>

However, the issue with using this path is that sometimes the image will fail to load. My guess is that the url is going through several redirects to fetch the actual image's url. This especially becomes more problematic if you're trying to load multiple images at the same. As such, I'm trying to see if I can retrieve the final path of the Special:FilePath url using ajax.

$.ajax({
    url:
      "https://www.mediawiki.org/wiki/Special:FilePath/Wikimedia_Hackathon_Prague_2019_-_Group_Photo_-_CLK_-_cropped.jpg",
    type: "GET",
    success: function (data) {
      console.log(data);
    }
  });

However, this never even reaches success, so I'm not certain what needs to happen.



Solution 1:[1]

If you want to use AJAX, try MediaWiki API (manual):

Generic JavaScript:

var api = "https://en.wikipedia.org/w/api.php"; 

var params = {
    action: "query",
    format: "json",
    prop: "imageinfo",
    iiprop: "url",
    titles: "File:Wikimedia Hackathon Prague 2019 - Group Photo - CLK - cropped.jpg"
};

api = api + "?origin=*";
Object.keys(params).forEach(function(key){api += "&" + key + "=" + params[key];});

fetch(api)
    .then(function(response){return response.json();})
    .then(function(response) {
        var pages = response.query.pages;
        for (var p in pages) {
            console.log(pages[p].title + " is at: " + pages[p].imageinfo[0].url);
        }
    })
    .catch(function(error){console.log(error);});

In MediaWiki environment:

var params = {
    action: 'query',
    format: 'json',
    prop: 'imageinfo',
    iiprop: 'url',
    titles: 'File:Wikimedia Hackathon Prague 2019 - Group Photo - CLK - cropped.jpg'
},
api = new mw.Api();

api.get( params ).done( function ( data ) {
    var pages = data.query.pages,
        p;
    for ( p in pages ) {
        console.log( pages[p].title + ' is at: ' + pages[p].imageinfo[0].url );
    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Mashin