Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize (minimize) jQuery AJAX calls

I have over 50 AJAX calls from different functions of my code. All these calls have a similar structure with different data/url/callback params:

var jqXHR = $.post('/dba/port.php', {
        mode: "del_wallfunds",
        pdata: cdata,
        wname: wName
    },
    function (data) {}, "json")
    .done(function (data) {
        var msg = data.msg;
        if (msg.indexOf("Error") == -1) {
            alertify.success(msg);
            delSelected(selGroup);
        } else {
            alertify.error(msg);
        }
    })
    .fail(function () {
        alertify.error("Error .....");
    });

I am thinking how to write a function that would return that var jqXHR to minimize the total size of the code. It is not a problem to pass all static variables like URL, error strings etc. But the problem is that all callback functions on ".done" are different and I don't know how to pass these callback functions as variables.

One way would be to call a single "universal" function on .done and pass a "switch" variable to that function, but it doesn't seem to be an elegant solution.

Any suggestions how to it in some elegant way?

Thanks

like image 279
user2723490 Avatar asked Oct 03 '22 15:10

user2723490


1 Answers

Either pass the done callback function as an argument when calling your function:

function ajaxCall(url, data, doneCallback) {
    return $.post(url, data, doneCallback, "json").fail(...);
    // or
    return $.post(url, data, function() {}, "json").done(doneCallback).fail(...);
}

var jqXhr = ajaxCall('yoururl.php', {key: 'value'}, function(data) {
    // do something
});

Or return the jqXhr object from the function, and assign the done callback then:

function ajaxCall(url, data) {
    return $.post(url, data, function() {}, "json").fail(...);
}

var jqXhr = ajaxCall('yoururl.php', {key: 'value'});
jqXhr.done(function(data) {
    // do something
});

Alternatively switch to using jQuery.ajax() instead, and pass the entire options object in:

function ajaxCall(options) {
    return $.ajax(options).fail(...);
}

var jqXhr = ajaxCall({
    url: 'yoururl.php',
    data: {key: 'value'},
    dataType: 'json'
});
jqXhr.done(function(data) {
    // do something
});
like image 198
Anthony Grist Avatar answered Oct 07 '22 20:10

Anthony Grist