User:Damyon Wiese/Ajax Service

From MoodleDocs

Ajax Service

In the past we have created ajax interactions, by adding javascript to the page that talks to many different ajax scripts on the server. The API for communicating with those scripts is different for each script - and each scripts has to be separately audited for security holes etc. In addition, the function that we call from ajax are probably useful to add as a webservice so others can use them too, but we haven't really done that.

The solution!

What if we had one ajax script that could call webservice functions? And a mechanism for whitelisting which functions were allowed? And a way to call multiple functions in a single request? And a standard mechanism for error handling?

It has arrived: MDL-49163

This issue adds a new standard web service that is displayed in the UI but cannot be edited or disabled. It allows ajax requests using the users current session to make direct calls to the whitelisted webservice functions via a single ajax script (lib/ajax/service.php). The requests and responses are all JSON encoded, and multiple requests/responses can be send in a single web request.

To make webservice functions available to call from ajax, they just need to be added to the 'Moodle ajax web service' configuration in lib/db/services.php (like the mobile service).

To call them use the amd module 'core/ajax' like this:

require(['core/ajax'], function(ajax) {
    var promises =[
        { 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

Note: there is a better implementation of the above example in 'core/str' which will return you all the strings in one handler.