better software through user-centered design

JavaScript Ajax Wrapper

This is a simple wrapper for keeping consistency in ajax calls. This happens to use jQuery ajax but the key to the wrapper is that the internal functionality can be re-written or a new library utilized across the board. I have always liked this idea but now cherish it due to recent dealings with ExtJS and their complete lack of backwards compatibility on every release.

MyNamespace.Ajax = {
//Setup ajax default properties
Defaults: {
type: ‘POST’,
url: ”,
contentType: ‘application/json; charset=utf-8’,
dataType: ‘json’,
success: function (result) { },
error: function () { }
},

// Global Post for any Ajax calls.
// This is meant to be a wrapper for the jQuery $.ajax method and should not be circumvented without great reason.
Post: function (options) {
options = $.extend(this.Defaults, options);
//Serialize the json object if it has not already been done.
if (options.data && typeof (options.data) == “object”) {
options.data = JSON.stringify(options.data);
}

$.ajax({
type: options.type,
url: options.url,
contentType: options.contentType,
dataType: options.dataType,
data: options.data,
success: function (result) {
if (options.success) {
options.success.apply(this, Array.prototype.slice.call(arguments));
}
},
complete: function (request, status) {
if (options.complete) {
options.complete.apply(this, Array.prototype.slice.call(arguments));
}
},
error: function (request, typeText) {
MyNamespace.Utilities.LogError(request.responseText);
if (options.error) {
options.error.apply(this, Array.prototype.slice.call(arguments));
}
}
});
}
};

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: