Add callAPI() function
parent
2b7265eaac
commit
f1b7ce288c
@ -0,0 +1,47 @@
|
||||
/*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Call an API function on the server.
|
||||
* @param {string} action
|
||||
* @param {array} data key: value array of arguments for the server.
|
||||
* @param {function} success Called with the JSON response object.
|
||||
* @param {function} failure Called with an error message string.
|
||||
* @return {undefined}
|
||||
*/
|
||||
function callAPI(action, data, success, failure) {
|
||||
return $.ajax({
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
url: SETTINGS["server"] + "/" + action,
|
||||
data: data,
|
||||
timeout: 5000,
|
||||
success: function (data, textStatus) {
|
||||
if (data.status === "OK") {
|
||||
success(data);
|
||||
} else if (data.status === "ERROR") {
|
||||
failure(data.msg);
|
||||
} else {
|
||||
failure("The server sent an invalid response.");
|
||||
}
|
||||
},
|
||||
error: function (xhr, textStatus, errorThrown) {
|
||||
switch (textStatus) {
|
||||
case "timeout":
|
||||
failure("Couldn't connect to the server (timeout).");
|
||||
break;
|
||||
case "error":
|
||||
failure("Couldn't connect to the server (error).");
|
||||
break;
|
||||
case "parseerror":
|
||||
failure("The server sent a malformed response.");
|
||||
break;
|
||||
default:
|
||||
failure("Couldn't connect to the server.");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue