Skip to content

Instantly share code, notes, and snippets.

@mattbontrager
Last active March 29, 2017 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbontrager/a7ade4973d5e01a45b6345c64e528a68 to your computer and use it in GitHub Desktop.
Save mattbontrager/a7ade4973d5e01a45b6345c64e528a68 to your computer and use it in GitHub Desktop.
Custom Ajax handler (with jQuery Promises)
var App = (function() {
/**
* a development flag to easily silence console.logging
* @type {Boolean}
*/
var development = true,
self;
return {
init: function init() {
self = (!self) ? this: self;
// do app initialization here
self.Ajax.init();
$.when(self.getInfo())
.then(self.populateElementsWithInfo)
.catch(self.OnError);
},
Ajax: {
init: function ajaxinit() {
// "spinner" in this case is whatever gif you have for user feedback, showing the app is busy retrieving something
$('#spinner').ajaxStart(function startajax() {
$(this).show();
}).ajaxStop(function stopajax() {
$(this).hide();
});
},
post: function ajaxpost(params) {
/**
* conditional to confirm params were passed to post
*
* @date 2017-03-29
* @author mattbontrager
* @param {object} API method to call along with values to pass
* @return {boolean} discontinue local execution of Ajax.post() if no params
*/
if (!params) {
!!development && console.error('no params passed to Ajax.post()');
return;
}
!!development && console.log("params passed to Ajax.post(): ", params);
/**
* caching ajax post into var for handling within jQuery Deferred Object (promise)
* @type {jQuery Deferred Object}
*/
var aPost = $.post('php/api.php', params);
/**
* optimized (terse) jQuery Deferred object/function to handle ajax post results
*
* @date 2017-03-29
* @author mattbontrager
* @param {object} the actual promise object to either resolve or reject depending upon the success/failure of the ajax call
* @return {object} the promise object (optionally including the return value or object).
*/
return $.Deferred(function deferredAjaxPost(postDfd) {
aPost.success(function postsuccess(json) {
// resolving the promise object (with the return values) inside the ajax success handler.
postDfd.resolve(json);
}).error(function posterror(responseText) {
App.OnError(responseText);
// rejecting the promise object (with the reason for the error) inside the ajax error handler. e.g. API has no method that was called
postDfd.reject(responseText);
}).fail(function postfail(responseText) {
// rejecting the promise object (with the reason for the failure) inside the ajax failure handler. e.g. communication error
postDfd.reject(responseText);
});
}).promise();
},
getJson: function getjson(params) {
/**
* conditional to confirm params were passed to post
*
* @date 2017-03-29
* @author mattbontrager
* @param {object} API method to call along with values to pass
* @return {null} discontinue local execution of Ajax.post() if no params
*/
if (!params) {
!!development && console.error('no params passed to Ajax.getJson()');
return;
}
var tnmsg,
gJSON = $.getJSON('php/api.php', params);
return $.Deferred(function deferredAjaxGetJson(gjDfd) {
gJSON.success(function getJsonSuccess(json) {
if (json) {
gjDfd.resolve(json);
} else {
gjDFD.reject();
}
}).fail(function getJsonFailure(responseText) {
App.OnError(responseText);
gjDfd.reject(responseText);
}).error(function getJsonError() {
for (var p in params) {
if (params.hasOwnProperty(p)) {
if (p) {
tnmsg += '<p>key: ' + p + ' ==> value: ' + params[p] + '</p>';
}
}
}
var errMsg = 'An unexpected communication error occurred while executing Ajax.getJson with these parameters: ' + tnmsg;
App.OnError(errMsg);
gjDfd.reject();
});
}).promise();
}
},
getInfo: function getInfo() {
!!development && console.log('in getInfo');
return $.Deferred(function(gidfd) {
$.when(self.Ajax.getJson({method: 'get_all_info'})).then(function(data) {
gidfd.resolve(data);
}).catch(function(err) {
gidfd.reject(err);
});
}).promise();
},
populateElementsWithInfo: function populateElementsWithInfo(info) {
!!development && console.log('in populateElementsWithInfo', info);
// find elements in DOM and populate them with info
},
OnError: function onError(errObj) {
/**
* ensure presence of an errObj/error message
*
* @date 2017-03-29
* @author mattbontrager
* @param {object || string} the error message
* @return {boolean} discontinue function execution if no error message
*/
if (!errObj) {
!!development && console.error('no errObj passed to OnError()');
return;
}
if (typeof errObj === 'object') {
/**
* if err message is an object, output the error in a more readable format in the console.
* https://developers.google.com/web/tools/chrome-devtools/console/console-reference#group
*/
console.group('error message');
for (var prop in errObj) {
if (errObj.hasOwnProperty(prop)) {
if (prop && errObj[prop] !== '') {
var propAsString = '' + prop + ': ';
console.log(propAsString, errObj[prop]);
}
}
}
console.groupEnd();
return;
} else if (typeof errObj === 'string') {
console.error(errObj);
return;
} else {
console.error('unknown error type: ', errObj);
return;
}
}
}
}());
$(function() {
App.init();
// example usage found in App.getInfo (automatically called in this case in App.init());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment