#REDIRECT [[Wikipedia:User scripts/Guide]]
[[Ajax (programming)|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 [[mw:MediaWiki 1.16|1.16 release]], MediaWiki comes with the [[jQuery]] library, which provides a convenient framework for easily making Ajax requests.
==Common problems==
* <p>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 <code>'''null'''</code>. This occurs because the script continued even though the query wasn't finished.</p><!--
--><p>To correct the problem, you need to use [[w:callback (computer science)|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.</p>
* 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 funtions which facilitate the use of its API. The main modules available are
* [https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/resources/mediawiki.api/mediawiki.api.js?view=markup mediawiki.api]
* [https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/resources/mediawiki.api/mediawiki.api.edit.js?view=markup mediawiki.api.edit]
If your script makes use any method or code provided by these modules, remember to indicate the dependencies with [[mw:ResourceLoader/Default_modules#mediaWiki.loader|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]].
<source lang="javascript">
$.ajax({
url: mw.util.wikiGetlink( 'Wikipedia:Sandbox' ),
success: function( data ) {
alert( 'The remote page contains:\n' + data );
},
error: function() {
alert( 'The ajax request failed.' );
}
});
</source>
=== Get the wikitext of a page ===
==== Using module <code>mediawiki.api</code>====
Note: make sure to add "mediawiki.api" to your dependencies!
<source lang="javascript">
function doSomethingWithText( wikitext ) {
/* .. */
alert( 'The wikitext of the page is:\n\n' + wikitext );
}
function doSomethingInCaseOfError () {
/* .. */
console.log( 'err' );
}
var api = new mw.Api();
api.get( {
prop: 'revisions',
rvprop: 'content',
rvlimit: 1,
indexpageids: true,
titles: 'Wikipedia:Sandbox'
}, {
ok: 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]['*'] );
}
},
err: doSomethingInCaseOfError
} );
</source>
==== Using plain jQuery ====
<source lang="javascript">
$.getJSON(
mw.util.wikiScript('api'),
'format=json&action=query&prop=revisions&rvprop=content&rvlimit=1&titles=Wikipedia:Sandbox',
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 );
</source>
===Edit a page and other common actions===
Scripts can perform common actions (like editing, protection, blocking, deletion, etc.) through the [{{SERVER}}/w/api.php 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 [{{SERVER}}/w/api.php API documentation].
<source lang="javascript">
// Edit page (must be done through POST)
function editPage( info ) {
$.ajax({
url: mw.util.wikiScript( 'api' ),
type: 'POST',
dataType: 'json',
data: {
format: 'json',
action: 'edit',
title: info.title,
text: info.text,
summary: info.summary,
token: mw.user.tokens.get( 'editToken' )
},
success: function( data ) {
if ( data && data.edit && data.edit.result && data.edit.result == 'Success' ) {
alert( 'Page edited!' );
} else {
alert( 'The edit query returned an error. =(' );
}
},
error: 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]]...'
});
</source>
==See also==
* [[mw:ResourceLoader/JavaScript Deprecations#ajax.js]]
* [[mw:ResourceLoader/Default modules#jQuery & plugins]]
|