views:

42

answers:

1

I'd like to know if there is a better approach to creating re-usable ajax object for jquery.

This is my un-tested code.

var sender = {
    function ajax(url, type, dataType,  callback) {
        $.ajax({
            url: url,
            type: type,
            dataType: dataType,
            beforeSend: function() {
                onStartAjax();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                callback.failure(XMLHttpRequest, textStatus, errorThrown);
            },
            success: function(data, textStatus) {
                callback.success(data, textStatus);
            },
            complete: function (XMLHttpRequest, textStatus) {
                onEndAjax();
            }
        });
    },
    function onStartAjax() {
        // show loader
    },
    function onEndAjax() {
        // hide loader
    }  
};


<script type="text/javascript">
    var callback = {
        success: function(data, textStatus) {
            $('#content').html(data);
        },
        failure: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')');
        }
    }

    sender.ajax(url, type, dataType, callback);

</script>
+4  A: 

You can set the basic options that you always have the same separately.

for instance if you always use the same thing here:

    type: type, 
    dataType: dataType, 

for those types, you can set them separately.

Here is how you do that type of thing:

$.ajaxSetup({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  data: "{}"
});

NOW those are set and you can simplify your individual ajax calls.

EDIT:

NOTE: Setting parameters to $.ajax override these defaults. Thus presetting “data” to an empty JSON string is safe and desired. This way, any $.ajax call that does specify a data parameter will function as expected, since the default will not be used. This helps avoid issues that can be difficult to find on a deployed site.

Mark Schultheiss
That's a good tip. However, I am more interested in a design pattern that's better than what I have.
Eeyore