AJAX pre 2.9

Jump to: navigation, search

Ajax in Moodle 2.8 and earlier

Moodle 2.8

The recommended way to perform AJAX interactions in Moodle 2.8 and earlier is described below. For information on writing AJAX interactions in the latest version of Moodle see AJAX .

Moodle has been using the YUI framework for many years. YUI provides libraries for communicating data with the server, and for parsing the output received. The key parts of the YUI library which do this are:

  • Y.IO
  • Y.JSON (Note: native browser implementations are used if available. Y.JSON is a monkey-patch for older browsers lacking this support natively but it does provide a hint as to the relevant functions.)

Writing server-side AJAX

Moodle 2.8

For JavaScript to communicate with the server-side aspect of Moodle, you need to create server-side scripts written in PHP. These should use standard moodle APIs and libraries. Any AJAX script in moodle must define the AJAX_SCRIPT variable before including moodle's configuration:

 define('AJAX_SCRIPT', true);

Doing so:

  • ensures that any exceptions that your code may generate are returned in json notation rather than an HTML output (this means that you can parse them in your code and use the JS error notification dialogues which exist in Moodle);
  • ensures that the correct document mime-type (application/json in most cases) is sent with the document (this can have important implications for some load balancers and reverse proxy implementations which attempt to inject additional content for certain mime-types); and
  • ensures that AJAX versions of renderers are used (this is discussed further below).

All responses from your script should ideally be returned in JSON notation.

A proposal being considered at present is to suggest that AJAX versions of scripts should perhaps be named as NAME.ajax.php or NAME.json.php to make their use clearer at a glance

AJAX renderers

Moodle 2.8

Since Moodle 2.0, AJAX output can be generated by creating an ajax renderer class named something like mod_forum_renderer_ajax in the same way and in the same file as the normal renderer. If a script is marked as being an AJAX script by having this line placed at the top of the file (before any other code)

 define('AJAX_SCRIPT', true);

then the AJAX renderer will be used in place of the main one for all components if it exists.

See also