user3210416
user3210416

Reputation: 804

How to minimize ajax calls functions

I have an function that has an ajax call and the data the same in both function. The ajax and the function works but I have several functions in the ajax that returns a lot of values. What I want to know is there a way to use the ajax function once and I can call certain functions within the ajax?

SO I WOULDN'T DO SOMETHING LIKE:

This ajax has a function call handleData

start = function(rowsInDB, ratio_Over_rows, lastx_gp){

    //ajax ONLY calls don't return anything
    (function($) {
    //Connects to the json file
    var url = 'XXX?';
    //Automatic refresh

    $.ajax({
    type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(data) {

        handleData(data, 7, 5, 5);

    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

}  

And another ajax with a different function called placeData, same data read from

plays = function(rowsInDB, ratio_Over_rows, lastx_gp){

    //ajax ONLY calls don't return anything
    (function($) {
    //Connects to the json file
    var url = 'http://beniky.co.uk/football/ast.json?callback=?';
    //Automatic refresh

    $.ajax({
    type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(data) {

        placeData(data, 7, 5, 5);

    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

}

Ps. I don't want both function in one ajax

Upvotes: 1

Views: 325

Answers (1)

code-jaff
code-jaff

Reputation: 9330

what about having like this

common = function (rowsInDB, ratio_Over_rows, lastx_gp, callback) {
    //ajax ONLY calls don't return anything
    (function ($) {
        //Connects to the json file
        var url = 'XXX?';
        //Automatic refresh
        $.ajax({
            type: 'GET',
            url: url,
            async: false,
            jsonpCallback: 'jsonCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function (data) {
                if (typeof callback == "function") {
                    callback(data, 7, 5, 5);
                }
            },
            error: function (e) {
                console.log(e.message);
            }
        });
    })(jQuery);
}

USAGE

common(rowsInDB, ratio_Over_rows, lastx_gp, handleData);
common(rowsInDB, ratio_Over_rows, lastx_gp, placeData);

Upvotes: 2

Related Questions