weekly release 3.6dev
[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
9bdcf579 22 * @class ajax
72f8324e
DW
23 * @package core
24 * @copyright 2015 Damyon Wiese <damyon@moodle.com>
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9bdcf579 26 * @since 2.9
72f8324e 27 */
671be2be
JO
28define(['jquery', 'core/config', 'core/log'], function($, config, Log) {
29
30 // Keeps track of when the user leaves the page so we know not to show an error.
31 var unloading = false;
72f8324e
DW
32
33 /**
34 * Success handler. Called when the ajax call succeeds. Checks each response and
35 * resolves or rejects the deferred from that request.
36 *
9bdcf579
DW
37 * @method requestSuccess
38 * @private
72f8324e
DW
39 * @param {Object[]} responses Array of responses containing error, exception and data attributes.
40 */
41 var requestSuccess = function(responses) {
42 // Call each of the success handlers.
43 var requests = this;
44 var exception = null;
45 var i = 0;
46 var request;
47 var response;
48
fa038116
AN
49 if (responses.error) {
50 // There was an error with the request as a whole.
51 // We need to reject each promise.
52 // Unfortunately this may lead to duplicate dialogues, but each Promise must be rejected.
53 for (; i < requests.length; i++) {
54 request = requests[i];
55 request.deferred.reject(responses);
56 }
57
58 return;
59 }
60
72f8324e
DW
61 for (i = 0; i < requests.length; i++) {
62 request = requests[i];
63
64 response = responses[i];
65 // We may not have responses for all the requests.
66 if (typeof response !== "undefined") {
67 if (response.error === false) {
68 // Call the done handler if it was provided.
69 request.deferred.resolve(response.data);
70 } else {
71 exception = response.exception;
72 break;
73 }
74 } else {
75 // This is not an expected case.
76 exception = new Error('missing response');
77 break;
78 }
79 }
80 // Something failed, reject the remaining promises.
81 if (exception !== null) {
82 for (; i < requests.length; i++) {
83 request = requests[i];
84 request.deferred.reject(exception);
85 }
86 }
87 };
88
89 /**
90 * Fail handler. Called when the ajax call fails. Rejects all deferreds.
91 *
9bdcf579
DW
92 * @method requestFail
93 * @private
72f8324e
DW
94 * @param {jqXHR} jqXHR The ajax object.
95 * @param {string} textStatus The status string.
fa038116 96 * @param {Error|Object} exception The error thrown.
72f8324e 97 */
fa038116 98 var requestFail = function(jqXHR, textStatus, exception) {
72f8324e
DW
99 // Reject all the promises.
100 var requests = this;
101
102 var i = 0;
103 for (i = 0; i < requests.length; i++) {
104 var request = requests[i];
105
671be2be
JO
106 if (unloading) {
107 // No need to trigger an error because we are already navigating.
fa038116
AN
108 Log.error("Page unloaded.");
109 Log.error(exception);
671be2be 110 } else {
fa038116 111 request.deferred.reject(exception);
671be2be 112 }
72f8324e
DW
113 }
114 };
115
116 return /** @alias module:core/ajax */ {
117 // Public variables and functions.
118 /**
119 * Make a series of ajax requests and return all the responses.
9bdcf579
DW
120 *
121 * @method call
c96f55e6 122 * @param {Object[]} requests Array of requests with each containing methodname and args properties.
72f8324e
DW
123 * done and fail callbacks can be set for each element in the array, or the
124 * can be attached to the promises returned by this function.
9bdcf579
DW
125 * @param {Boolean} async Optional, defaults to true.
126 * If false - this function will not return until the promises are resolved.
ba224fb4
DW
127 * @param {Boolean} loginrequired Optional, defaults to true.
128 * If false - this function will call the faster nologin ajax script - but
129 * will fail unless all functions have been marked as 'loginrequired' => false
130 * in services.php
9bdcf579 131 * @return {Promise[]} Array of promises that will be resolved when the ajax call returns.
72f8324e 132 */
ba224fb4 133 call: function(requests, async, loginrequired) {
671be2be
JO
134 $(window).bind('beforeunload', function() {
135 unloading = true;
136 });
72f8324e
DW
137 var ajaxRequestData = [],
138 i,
c1ac8e7f
TH
139 promises = [],
140 methodInfo = [],
141 requestInfo = '';
9bdcf579 142
4093d643
DW
143 if (typeof loginrequired === "undefined") {
144 loginrequired = true;
145 }
9bdcf579
DW
146 if (typeof async === "undefined") {
147 async = true;
148 }
72f8324e
DW
149 for (i = 0; i < requests.length; i++) {
150 var request = requests[i];
151 ajaxRequestData.push({
152 index: i,
153 methodname: request.methodname,
154 args: request.args
155 });
156 request.deferred = $.Deferred();
157 promises.push(request.deferred.promise());
158 // Allow setting done and fail handlers as arguments.
159 // This is just a shortcut for the calling code.
160 if (typeof request.done !== "undefined") {
161 request.deferred.done(request.done);
162 }
163 if (typeof request.fail !== "undefined") {
164 request.deferred.fail(request.fail);
165 }
166 request.index = i;
c1ac8e7f
TH
167 methodInfo.push(request.methodname);
168 }
169
170 if (methodInfo.length <= 5) {
171 requestInfo = methodInfo.sort().join();
172 } else {
173 requestInfo = methodInfo.length + '-method-calls';
72f8324e
DW
174 }
175
176 ajaxRequestData = JSON.stringify(ajaxRequestData);
177 var settings = {
178 type: 'POST',
179 data: ajaxRequestData,
180 context: requests,
181 dataType: 'json',
9bdcf579 182 processData: false,
023d6a67
BK
183 async: async,
184 contentType: "application/json"
72f8324e
DW
185 };
186
c1ac8e7f 187 var script = 'service.php';
ba224fb4 188 if (!loginrequired) {
c1ac8e7f 189 script = 'service-nologin.php';
ba224fb4 190 }
c1ac8e7f
TH
191 var url = config.wwwroot + '/lib/ajax/' + script +
192 '?sesskey=' + config.sesskey + '&info=' + requestInfo;
ba224fb4 193
9bdcf579
DW
194 // Jquery deprecated done and fail with async=false so we need to do this 2 ways.
195 if (async) {
c1ac8e7f 196 $.ajax(url, settings)
9bdcf579
DW
197 .done(requestSuccess)
198 .fail(requestFail);
199 } else {
200 settings.success = requestSuccess;
201 settings.error = requestFail;
c1ac8e7f 202 $.ajax(url, settings);
9bdcf579 203 }
72f8324e
DW
204
205 return promises;
206 }
207 };
208});