Pjottur Pjottur - 20 days ago 7
Javascript Question

Bind event to jQuery.post and callbacks

I am using jQuery.post a lot in my project and everytime the browser sends a post request, I want to show a preloader while the request is in process and then stop the preloader when i get the reply form the server:

var params = {'action':'get_customer_info', 'customerID':4};

preloader.start();
$.post('ajax/url', params, function(response){
preloader.stop();

responseHandler(response);
});


Instead of adding the preloader.start() and preloader.stop() lines every time I call jQuery's post, I'd like to bind/trigger events on before the jQeury.post as well on the success/fail handlers.

I know how to bind and trigger events in general, but I'm not sure how I would do this with the $.post and handlers.

How do I do this?

Answer

You could set up the global ajax events, that way the preloader shows on every ajax request

$(document).ajaxSend(function() {
    preloader.start();
}).ajaxComplete(function() {
    preloader.stop();
});

Or you could create your own post function

function post(url, params) {
    preloader.start();
    return $.post('ajax/url', params, function(response){
        preloader.stop();
    });
}

To be used like

post('ajax/url', params).done(function(response) {
    responseHandler(response);
});
Comments