From f1b7ce288c78f344025b9399847165e94d6d0752 Mon Sep 17 00:00:00 2001 From: Skylar Ittner Date: Tue, 26 Mar 2019 14:14:48 -0600 Subject: [PATCH] Add callAPI() function --- www/js/api.js | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 www/js/api.js diff --git a/www/js/api.js b/www/js/api.js new file mode 100644 index 0000000..99912b4 --- /dev/null +++ b/www/js/api.js @@ -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."); + } + } + }); +} \ No newline at end of file