Purus
Purus

Reputation: 5799

Generic $.ajax() call function for resusability

I am creating a application where I have lot of ajax calls to a remote server and use them extensively. As the code is almost same in all calls, I want to create a new function which I can reuse. I am struck up in defining the parameter structure for the "data" parameter. I will explain below my problem.

Sample of my current ajax call is provided below.

Current Call Sample:

$.ajax({
    beforeSend: function() {
        $.mobile.loading('show');
    },
    complete: function() {
        $.mobile.loading('hide');
    },
    type: 'GET',
    url: 'http://localhost/test-url/',
    crossDomain: true,
    data: {appkey: '1234567', action: 'action1','name':'me'},
    dataType: 'jsonp',
    contentType: "application/javascript",
    jsonp: 'callback',
    jsonpCallback: 'mycallback',
    async: false,
    error: function() {
        //some operations
    },
    success: function(data) {
        //some operations
    }
});

The re-usable function that I have created:

function newAjax(parm, successCallback, errorCallback) {
    $.ajax({
        beforeSend: function() {
            $.mobile.loading('show');
        },
        complete: function() {
            $.mobile.loading('hide');
        },
        type: 'GET',
        url: 'http://localhost/test-url',
        crossDomain: true,
        data: {appkey: '1234567', parm: parm},
        dataType: 'jsonp',
        contentType: "application/javascript",
        jsonp: 'callback',
        jsonpCallback: 'mycallback',
        async: false,
        success: function() {
            successCallback();
        },
        error: function() {
            errorCallback();
        }
    });
}

Question:

Upvotes: 2

Views: 4686

Answers (1)

Matt
Matt

Reputation: 75307

  1. You can use the jQuery.extend method to combine two or more objects together.

    data: jQuery.extend({appkey: '1234567'}, parm),
    
  2. You can check that you were actually passed functions for successCallback and errorCallback using typeof var === 'function';

    success: function () {
        if (typeof successCallback === 'function') {
            successCallback();
        }
    }, 
    
    error: function () {
        if (typeof errorCallback === 'function') {
            errorCallback();
        }
    }
    

    ... although it might be nicer if you just returned the Promise created by the AJAX request, and let the caller add their success, error handlers if they wanted;

    function newAjax(parm) {
       return jQuery.ajax({
           /* as before, but without success and error defined */
       });
    }
    

    ... then:

    newAjax().done(function () {
        // Handle done case
    }).fail(function () {
        // Handle error case.
    });
    

    If a caller doesn't want to add an error handler, they just don't call fail();

    newAjax().done(function () {
        // Handle done case
    });
    

Upvotes: 5

Related Questions