Wikipedia:WikiProject User scripts/Guide/Ajax
AJAX (asynchronous JavaScript and XML) is a popular name for a web programming technique that queries the server or fetches content without reloading the entire page.
While programming AJAX can be complex, libraries of functions can make it much easier. Since the 1.16 release, MediaWiki comes with the jQuery library, which provides a convenient framework for easily making Ajax requests.
Common problems
AJAX programmers commonly run into problems if they don't account for AJAX's asynchronicity. If you try to pop up a box with another page's content, you will almost certainly pop up a box containing
null
. This occurs because the script continued even though the query wasn't finished.To correct the problem, you need to use callback functions. Place the next portion of code after a query into a function, and call the function when the query completes. jQuery makes this very easy to do.
- AJAX scripts cannot reach a page on a different server (for example, google.ca or en.wikisource.org from en.wikipedia.org). Trying to do so will cause the script to halt with or without error. This can be circumvented using a proxy on the current server, but none is available for Wikimedia user scripts.
Basic examples
MediaWiki provides some modules with helper functions which facilitate the use of its API. The main modules available are
If your script makes use any method or code provided by these modules, remember to indicate the dependencies with mw.loader.using or, in case of gadgets, on its definition at MediaWiki:Gadgets-definition.
Fetch page content
Fetching a page content can be done using GET.
$.ajax({
url: mw.util.wikiGetlink( 'Wikipedia:Sandbox' )
})
.done(function( data ) {
alert( 'The remote page contains:\n' + data );
})
.fail(function() {
alert( 'The ajax request failed.' );
});
Get the wikitext of a page
Using module mediawiki.api
Note: make sure to add "mediawiki.api" to your dependencies!
function doSomethingWithText( wikitext ) {
/* .. */
alert( 'The wikitext of the page is:\n\n' + wikitext );
}
function doSomethingInCaseOfError () {
/* .. */
console.log( 'err' );
}
(new mw.Api()).get( {
prop: 'revisions',
rvprop: 'content',
rvlimit: 1,
indexpageids: true,
titles: 'Wikipedia:Sandbox'
} )
.done( function ( data ) {
var q = data.query,
id = q && q.pageids && q.pageids[0],
pg = id && q.pages && q.pages[ id ],
rv = pg && pg.revisions;
if ( rv && rv[0] && rv[0]['*'] ) {
doSomethingWithText( rv[0]['*'] );
}
} )
.fail( doSomethingInCaseOfError );
Using plain jQuery
$.getJSON(
mw.util.wikiScript('api'),
{
format: 'json',
action: 'query',
prop: 'revisions',
rvprop: 'content',
rvlimit: 1,
titles: 'Wikipedia:Sandbox'
}
)
.done(function ( data ) {
var page, wikitext;
try {
for ( page in data.query.pages ) {
wikitext = data.query.pages[page].revisions[0]['*'];
doSomethingWithText( wikitext );
}
} catch ( e ) {
doSomethingInCaseOfError();
}
})
.fail( doSomethingInCaseOfError );
Edit a page and other common actions
Scripts can perform common actions (like editing, protection, blocking, deletion, etc.) through the API. These actions require an edit token, which is valid for any action during the same session. (However, you should get a new token for different tasks in case this changes in the future.)
The code below shows how to edit a page, but it can easily be adapted to other actions by reading the API documentation.
// Edit page (must be done through POST)
// the line "text: info.text," will cause the call
// to replace entire page content with supplied data.
// alternatively, one can append or prepend the data to the page, by using
// "appendtext: info.text," or "prependtext: info.text," instead.
when using "appendtext", it is possible to append the text to s specific section,
// by setting the optional field "section".
function editPage( info ) {
$.ajax({
url: mw.util.wikiScript( 'api' ),
type: 'POST',
dataType: 'json',
data: {
format: 'json',
action: 'edit',
title: info.title,
text: info.text, // will replace entire page content
summary: info.summary,
token: mw.user.tokens.get( 'editToken' )
}
})
.done (function( data ) {
if ( data && data.edit && data.edit.result && data.edit.result == 'Success' ) {
alert( 'Page edited!' );
} else {
alert( 'The edit query returned an error. =(' );
}
})
.fail ( function() {
alert( 'The ajax request failed.' );
});
}
editPage({
title: 'User:' + mw.config.get( 'wgUserName' ) + '/Sandbox',
text: 'Cool! It works! :-) ~~' + '~~',
summary: 'Trying to edit my sandbox [[Project:WikiProject User scripts/Guide/Ajax|using AJAX]]...'
});