Wikipedia:WikiProject User scripts/Guide/Ajax

This is an old revision of this page, as edited by Kangaroopower (talk | contribs) at 02:19, 26 April 2012 (Removed all the old stuff because, some ppl might just use them and then their scripts will break soon- feel free to rv, just message me on my talk). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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 funtions 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' ),
	success: function( data ) {
		alert( 'The remote page contains:\n' + data );
	},
	error: function() {
		alert( 'The ajax request failed.' );
	}
});

Get the wikitext of a page

Using module mediawiki.api (make sure to add this to your dependencies!)
function ok( wikitext ) {
	/* .. */
	alert( 'The wikitext of the page is:\n\n' + wikitext );
}
function err () {
	/* .. */
	console.log( 'err' );
}
var api = new mw.Api();
api.get( {
	action: 'query',
	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]['*'] ) {
			ok( rv[0]['*'] );
		}
	},
	err: err
} );
Using plain jQuery
$.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]['*'];
				ok( wikitext );
			}
		} catch ( e ) {
			err();
		}
	}
).fail( err );

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)
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]]...'
});


Data sources

See mw:API. Usually used with JSON format.

HTML

You could fetch the whole article page or use &action=render URL parameter to get the content without all the menus (example). Also see Parameters to index.php.

The result you could treat as a text but it's usually convenient to parse it as HTML document, e.g. using DOMParser object (examples needed).

Wiki code

To get the wiki code you use &action=raw URL parameter (example).

The result you treat as a text.

Preview

Sometimes you might want to use preview. For example, Special:Prefixindex won't work with &action=render. To get rid of the unnecessary menus you could submit {{Special:Prefixindex/somepage}} for a preview and get a "clean" list (nevertheless, it's better to use API for prefix index)

See also