Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a specific function on every ajax request

I have a problem, that I have several pages in my project and I used a lot of ajax requests in my project, but now I think that whenever an ajax request is called a function will called and whenever that request ends another function will call. How can I do this globally I know I can put this in every ajax request but I need a solution which I do in one place and it works all over the project.

$(document).read(function(){
 // Suppose this document load function is written on layout page and every page is  inherited from this page
});
like image 345
Ahsan Avatar asked May 09 '12 08:05

Ahsan


3 Answers

Use ajaxSetup, for example

$.ajaxSetup({
    beforeSend: function() {
        console.log('test');
    },
    complete: function() {
        console.log('completed');
    }
});

will setup beforeSend handler for every ajax request. Note that ajaxSetup can take any option that $.ajax can.

like image 58
freakish Avatar answered Nov 14 '22 22:11

freakish


You should create a wrapper function for your ajax, then use that function. that way, you have "central" control over the ajax call. something like:

//fast and crude way to extend jQuery
$.fn.customAjax = function(params){

    //contains defaults and predefined functions
    var defaults = {
        complete : function(){...default complete hander...},
        beforeSend : function (){...default beforeSend handler}
        ...
    }

    //merge settings
    var finalParams = $.extend({},defaults,params);

    //call ajax and return the deferred
    return $.ajax(finalParams);
}

//use it like
$.customAjax({
   url : ...,
   method : ...,
   data: ...,
   complete : function(){...} //redefining in the call will override the defaults
});
like image 36
Joseph Avatar answered Nov 14 '22 20:11

Joseph


.ajaxStart

Register a handler to be called when the first Ajax request begins.

.ajaxSucess

Attach a function to be executed whenever an Ajax request completes successfully.

for Detail doc: http://api.jquery.com/category/ajax/

like image 32
tuoxie007 Avatar answered Nov 14 '22 22:11

tuoxie007