Wikipedia:WikiProject User scripts/Guide/Ajax

From Wikipedia, the free encyclopedia


Contents

[edit] XMLHttpRequest

Usual approach for creating cross-browser XMLHttpRequest object is
if (window.XMLHttpRequest) ... else if (window.ActiveXObject) ....

However, built-in ajax.js already has this code, so userscripts can simply use

xmlhttp = sajax_init_object()

[edit] Data sources

[edit] api.php

See mw:API. Usually used with JSON format.

[edit] query.php

See User:Yurik/Query_API. This is older verison of API, can be used for some queries not yet implemented in API. Some Javascript examples can be found at User:Yurik/Query_API/User_Manual#JavaScript. As of early 2008, query.php was soon to be obsoleted: [1].

[edit] 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).

[edit] Wiki code

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

The result you treat as a text.

[edit] 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)

[edit] Implementations

[edit] Mediawiki


AjaxFunctions.php has 2 main functions:

  • wfAjaxWatch - server part of ajaxwatch.js
  • wfSajaxSearch - disabled on WMF projects. If it was enabled, ajaxsearch.js would be responsible for the client side. Also see mw:Manual:$wgAjaxSearch.


Another disabled feature is Live preview (preview.js)

[edit] Userscripts

[edit] Misc

Some alternatives to XMLHttpRequest:

  • IFrame: almost nobody uses this, but if you're interested, here's a small library: User:TheFearow/ajax.js (Warning: Untested)
  • URL actions: this is not Ajax at all, but this method is also widely used for one-click-do-all scripts. 1st part of the script goes to another page using additional "dummy" URL parameters (not recognized and so ignored by Mediawiki). 2nd part of the script analyzes that URL and then does something. Because of the way MediaWiki redirects after edits, cookies may also be used to transfer data and instructions. An example library (unmaintaned) can be found at User:Lupin/autoedit.js