I'm trying to fetch some data from Wikipedia via AJAX. After fiddling with the API for a while, I got to the point where my request URL actually displays what I need, which is the text from a certain section. But my AJAX request fails to return it. Here is my function:
function getSectionText(page, section) {
$.getJSON(
'http://en.wikipedia.org/w/api.php?action=query', {
prop: 'revisions',
rvlimit: '1',
rvsection: section,
rvprop: 'content',
format: 'json',
titles: page
},
function(data) {
return data;
}
)
}
This has nothing to do with origins, since I'm launching my function from a Wikipedia page, using Chrome's JS console. Yet, when I write var someVariable = getSectionText(wgPageName, someNumber)
, and then try to call someVariable
, Chrome says it is "undefined". Help please!
An example URL: my sandbox, first section.
AJAX is asynchronous! You cannot return the data from $.getJSON
. You need to do everything related to the returned JSON inside the callback.
function getSectionText(page, section) {
$.getJSON(
'http://en.wikipedia.org/w/api.php?action=query', {
prop: 'revisions',
rvlimit: '1',
rvsection: section,
rvprop: 'content',
format: 'json',
titles: page
},
function(data) {
console.log(data);
}
);
}
Or, you can use the promise
object returned, and attach a callback to that.
function getSectionText(page, section) {
return $.getJSON(
'http://en.wikipedia.org/w/api.php?action=query', {
prop: 'revisions',
rvlimit: '1',
rvsection: section,
rvprop: 'content',
format: 'json',
titles: page
}
);
}
getSectionText('User:Bluefire272', 1).done(function(data){
// You can use your data here
})