I'm trying to display a random Wikipedia article. I have an ajax request for a random page ID and an inner ajax request to parse the text of that page ID. I get a random page ID every time, but when I try to display it with the inner ajax request, all that is displayed is the "other languages" section.
I am using the call specified by the Wikipedia API sandbox, but I'm not getting the same result that is shown on that page. Any insight?
Here's my function:
$(document).ready(function () { //document.ready
$('#random-btn').click(function() { //random-btn click
$.ajax ({ //ajax random page
url: "http://www.mediawiki.org/w/api.php",
jsonp: "callback",
dataType: 'jsonp',
data: {
action: "query",
format: "json",
list: "random",
},
success: function (randomPage) { //random page success
var randomID = randomPage.query.random[0].id.toString();
console.log(randomID);
$.ajax ({ //ajax display given page
url: "http://www.mediawiki.org/w/api.php?action=parse&format=json&pageid=367435",
jsonp: "callback",
dataType: 'jsonp',
data: {
action: "parse",
format: "json",
pageids: randomID,
},
success: function (jsonObject) { //display success
var displayText = jsonObject.parse.text["*"];
$('#display').html(displayText);
} //display success
}) //ajax display given page
} //random page success
}) //ajax random page
}) //random-btn click
}) //document.ready
You can do all this also by using generator with extracts property in one request. Check parameters for more options.
$(document).ready(function () {
$('#random-btn').click(function () {
$('#display').empty();
$.ajax({
url: 'http://www.mediawiki.org/w/api.php',
dataType: 'jsonp',
data: {
action: 'query',
format: 'json',
generator: 'random',
prop: 'extracts',
grnnamespace: 0,
explaintext: true
},
success: function (result) {
var pages = result.query.pages;
var page = pages[Object.keys(pages)[0]];
$('#display').append($('<h2>').text(page.title));
$('#display').append($('<p>').text(page.extract));
}
});
});
});
<!DOCTYPE html>
<html>
<body>
<button id="random-btn">Get random</button>
<div id="display"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>