Isolating JQuery AJAX calls using JQuery 1.5 Deferred Objects


Usually when working on the interface for an application, there are multiple items which require an $.ajax call of some sort. Auto Complete fields, tables, drop downs, combo boxes, you get the idea. Now, before I learned about JQuery deferred objects, I would have an $.ajax call inside of my event handler methods. I know it's not the best way, but it's the most straightforward way I could implement it when I first began to use JQuery. The code ended up looking like the following:

cmdAddUser.click(function () {
var useridToAdd = $("#newUserIdToAdd").val();
var messageContainer = $("#messageContainer");
$.ajax({
type: "POST",
url: "/service/users/add",
dataType: "json",
data: {
userid: useridToAdd
},
success: function (data) {
var statusCode = data.response.status_code;
messageContainer.html('');
switch (statusCode) {
case "200":
messageContainer.addClass('ui-state-highlight');
messageContainer.html('<ul><li>' + data.response.status_message + '</li></ul>');
break;
default:
var messages = '<ul>';
$.each(data.response.errors, function (index, value) {
messages += '<li><pre>' + value + '</pre></li>';
});
messages += '</ul>';
messageContainer.html(messages);
break;
}
},
error: function (xhr, s, e) {
alert(s.error_status);
}
});
});

That's a pretty ugly snippet of code.

However, with the Deferred Objects introduced in JQuery 1.5 I can clean up that code:
function addUser(messagesContainer, newUserParameters) {
return $.post('/service/users/add', newUserParameters).error(function (xhr) {
var jsonData = $.parseJSON(xhr.responseText);
// this is a generic error reporting function
reportErrors(messagesContainer, jsonData.response.errors);
});
};

cmdAddUser.click(function () {
var useridToAdd = $("#newUserIdToAdd").val();
var messageContainer = $("#messageContainer");
var c = addUser(messageContainer, {
userid: useridToAdd
});
c.success(function (data) {
messageContainer.addClass('ui-state-highlight');
messageContainer.html('<ul><li>' + data.response.status_message + '</li></ul>');
});
});
With the $.ajax call isolated, I can now use this call in multiple places through out the site without having to repeat the code. It's nice and DRY (Don't Repeat Yourself...Dum Dum) now.