User:Pathoschild/Coding AJAX

From Wikipedia, the free encyclopedia
Jump to: navigation, search

This page gathers notes for JavaScript developers interested in coding user scripts for MediaWiki.

What is AJAX?[edit]

AJAX is a JavaScript programming technique for asynchronously fetching XML. It is most commonly used for fetching content from another page, and updating the current page without reloading.

This page assumes you already understand the concepts and have a working understanding of JavaScript. If you don't, see external tutorials:

Important considerations[edit]

Asynchronous[edit]

A major challenge to coding AJAX is that queries are launched synchronously: your script will not stop and wait for the query to complete. (The Asynchronous in AJAX refers to JavaScript and XML, not queries and the script.)

Aany code after the query may be run before the fetched content is available. For example, the following pseudocode will most likely fail. The script launches the AJAX query, then immediately alerts myText before the query completes and assigns it the desired value.

var myText = query_article_content('foo');
alert(myText);

This problem can be solved using modularization.

Best practices[edit]

Encapsulation[edit]

As much as possible, place code to perform a specific task into a function and call that. AJAX code can be highly repetitive and verbose, particularly because different browsers implement it differently. Encapsulation dramatically increases readability, and eases editing and debugging.

For example, the following code (which simply creates the object) is confusing and very difficult to reuse:

var myQuery;
try {
	// Try the new style before ActiveX so we don't
	// unnecessarily trigger warnings in IE 7 when
	// set to prompt about ActiveX usage
	myQuery = new XMLHttpRequest();
	} catch (e) {
		try {
			myQuery = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				myQuery = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (oc) {
				myQuery = null;
			}
		}
	}
}

In contrast, the following code is very readable and easy to reuse:

var myQuery = sajax_init_object();

(The sajax_init_object() function is defined by MediaWiki, so you can use it without worrying about how it works.)

Modularization[edit]

Break your scripts into blocks, and only call them when they're needed. A common mistake is to use procedural programming with AJAX queries, which is very messy and difficult to scale. For example, consider the following simple script:

var queryXML = sajax_init_object();
 
/* get first page */
queryXML.open('GET',myUrl,true);
queryXML.send('');
queryXML.onreadystatechange = function() {
	if(queryXML.readyState==4) {
		// success
		if(queryXML.status==200) {
			alert(queryXML.responseXML);
 
			/* get next page */
			queryXML = sajax_init_object();
 
			queryXML.open('GET',myUrl,true);
			queryXML.send('');
			queryXML.onreadystatechange = function() {
				if(queryXML.readyState==4) {
					// success
					if(queryXML.status==200) {
						alert(queryXML.responseXML);
					}
					// fail
					else {
						alert('Second query failed, aborting!');
					}
				}
			}
		}
		// fail
		else {
			alert('First query failed, aborting!');
		}
	}
}

Contrast the above script to the following modularized script:

 

Documentation by example[edit]

The following code shows by example, with ample comments, how to code a simple AJAX fetch script.

 // will do