Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

AJAX: Difference between revisions

From MoodleDocs
m (Protected "AJAX": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
 
(23 intermediate revisions by 8 users not shown)
Line 1: Line 1:
'''AJAX (Asynchronous Javascript and XML)''' is a modern web design technique that allows for more interactivity by making webpages that fetch data in the background and alter themselves without reloading the entire page. This helps to make a page feel much more like an application than a web page. AJAX is a new way of working with existing technologies (including HTML, [[Javascript]], [[CSS]] and the ''XMLHttpRequest object'' amongst others) rather than a new piece of technology in itself.
{{Template:Migrated|newDocId=/docs/guides/javascript/ajax/}}
 
Although AJAX indicates that XML is used, the term really relates to the group of technologies and in Moodle we tend to favour use of JSON rather than XML as the syntax is lighter and leads to a smaller output. It is also easier to construct from php data structures.
 
== Ajax in Moodle 2.9 and later ==
{{ Moodle 2.9 }}
 
In Moodle 2.9 we introduced a new way of writing AJAX interactions. This consists of a javascript module + php script that can call existing web service functions.
 
So the steps required to create an ajax interaction are:
 
# Write or find an existing web service function to handle the ajax interaction: See [[ Web_services ]]
# White list the web service for ajax. To do this, a new function needs to be added to the external service class "<methodname>_is_allowed_from_ajax() { return true; }". Only functions that are whitelisted using this mechanism will be available to the ajax script.
# Call the web service from javascript in response to a user interaction:
 
Example calling core_get_string:
<code javascript>
require(['core/ajax'], function(ajax) {
    var promises = ajax.call([
        { methodname: 'core_get_string', args: { component: 'mod_wiki', stringid: 'pluginname' } },
        { methodname: 'core_get_string', args: { component: 'mod_wiki', stringid: 'changerate' } }
    ]);
 
  promises[0].done(function(response) {
      console.log('mod_wiki/pluginname is' + response);
  }).fail(function(ex) {
      // do something with the exception
  });
 
  promises[1].done(function(response) {
      console.log('mod_wiki/changerate is' + response);
  }).fail(function(ex) {
      // do something with the exception
  });
});
</code>
Note: Don't actually fetch strings like this, it is just an example, use the 'core/str' module instead.
 
In Moodle 2.9 and later, to update parts of the UI in response to Ajax changes, consider using [[ Templates ]]
 
== 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.
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:
 
* [http://yuilibrary.com/yui/docs/api/classes/IO.html Y.IO]
* [http://yuilibrary.com/yui/docs/api/classes/JSON.html 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 ==
 
* [[Templates]]
* [[Javascript Modules]]
* [[Javascript FAQ]]
* [[Javascript]]
* [[Hijax]]
* [[Firebug#Debugging_AJAX_with_Firebug|Debugging AJAX with Firebug]]
 
 
* [http://www.adaptivepath.com/publications/essays/archives/000385.php ''Ajax: A New Approach to Web Applications'', the original Ajax article by Adaptive Path]
* [http://developer.mozilla.org/en/docs/AJAX:Getting_Started ''AJAX: Getting Started'' article on developer.mozilla.org]
* [http://www.sourcelabs.com/blogs/ajb/2005/12/10_places_you_must_use_ajax.html ''10 places you must use AJAX'' by Adam Bosworth]
* [http://www-128.ibm.com/developerworks/web/library/wa-ajaxtop1/?ca=dgr-lnxw01AjaxHype ''Considering Ajax, Part 1: Cut through the hype'' from IBM developerworks]
* [http://en.wikipedia.org/wiki/Ajax_%28programming%29 Wikipedia article on ''AJAX'']
* [http://www.maxkiesler.com/index.php/weblog/comments/how_to_make_your_ajax_applications_accessible/ How to Make Your AJAX Applications Accessible: 40 Tutorials and Articles]
*[http://www.ajaxload.info/ AJAX loading icon generator]
 
[[Category:Javascript]]
[[Category:AJAX]]

Latest revision as of 12:45, 9 December 2022

Important:

This content of this page has been updated and migrated to the new Moodle Developer Resources. The information contained on the page should no longer be seen up-to-date.

Why not view this page on the new site and help us to migrate more content to the new site!