MDL-49163 Webservices, AJAX: Add support for a new ajax webservice handler.
[moodle.git] / lib / amd / src / ajax.js
CommitLineData
72f8324e
DW
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Standard Ajax wrapper for Moodle. It calls the central Ajax script,
18 * which can call any existing webservice using the current session.
19 * In addition, it can batch multiple requests and return multiple responses.
20 *
21 * @module core/ajax
22 * @package core
23 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26define(['jquery', 'core/config'], function($, config) {
27
28 /**
29 * Success handler. Called when the ajax call succeeds. Checks each response and
30 * resolves or rejects the deferred from that request.
31 *
32 * @param {Object[]} responses Array of responses containing error, exception and data attributes.
33 */
34 var requestSuccess = function(responses) {
35 // Call each of the success handlers.
36 var requests = this;
37 var exception = null;
38 var i = 0;
39 var request;
40 var response;
41
42 for (i = 0; i < requests.length; i++) {
43 request = requests[i];
44
45 response = responses[i];
46 // We may not have responses for all the requests.
47 if (typeof response !== "undefined") {
48 if (response.error === false) {
49 // Call the done handler if it was provided.
50 request.deferred.resolve(response.data);
51 } else {
52 exception = response.exception;
53 break;
54 }
55 } else {
56 // This is not an expected case.
57 exception = new Error('missing response');
58 break;
59 }
60 }
61 // Something failed, reject the remaining promises.
62 if (exception !== null) {
63 for (; i < requests.length; i++) {
64 request = requests[i];
65 request.deferred.reject(exception);
66 }
67 }
68 };
69
70 /**
71 * Fail handler. Called when the ajax call fails. Rejects all deferreds.
72 *
73 * @param {jqXHR} jqXHR The ajax object.
74 * @param {string} textStatus The status string.
75 */
76 var requestFail = function(jqXHR, textStatus) {
77 // Reject all the promises.
78 var requests = this;
79
80 var i = 0;
81 for (i = 0; i < requests.length; i++) {
82 var request = requests[i];
83
84 if (typeof request.fail != "undefined") {
85 request.deferred.reject(textStatus);
86 }
87 }
88 };
89
90 return /** @alias module:core/ajax */ {
91 // Public variables and functions.
92 /**
93 * Make a series of ajax requests and return all the responses.
94 * @param {Object[]} Array of requests with each containing methodname and args properties.
95 * done and fail callbacks can be set for each element in the array, or the
96 * can be attached to the promises returned by this function.
97 * @return {Promise{}} Array of promises that will be resolved when the ajax call returns.
98 */
99 call: function(requests) {
100 var ajaxRequestData = [],
101 i,
102 promises = [];
103 for (i = 0; i < requests.length; i++) {
104 var request = requests[i];
105 ajaxRequestData.push({
106 index: i,
107 methodname: request.methodname,
108 args: request.args
109 });
110 request.deferred = $.Deferred();
111 promises.push(request.deferred.promise());
112 // Allow setting done and fail handlers as arguments.
113 // This is just a shortcut for the calling code.
114 if (typeof request.done !== "undefined") {
115 request.deferred.done(request.done);
116 }
117 if (typeof request.fail !== "undefined") {
118 request.deferred.fail(request.fail);
119 }
120 request.index = i;
121 }
122
123 ajaxRequestData = JSON.stringify(ajaxRequestData);
124 var settings = {
125 type: 'POST',
126 data: ajaxRequestData,
127 context: requests,
128 dataType: 'json',
129 processData: false
130 };
131
132 $.ajax(config.wwwroot + '/lib/ajax/service.php', settings)
133 .done(requestSuccess)
134 .fail(requestFail);
135
136 return promises;
137 }
138 };
139});