Search code examples
javascriptjqueryajaxajaxform

Using beforeSend and complete in every instance of ajaxForm globally


I am trying to use the beforeSend and complete functions on all ajaxForms in a project. I would like to do this without adding the exact bit a code all throughout the project.

I've been able to accomplish this with the below code on a per form basis.

           beforeSend: function() {
                $('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
            },
            complete: function(xhr) {
                $('.lightbox#page-loader').remove()
            },  

I'd like to be able to put that code into one place that executes every time an ajaxForm is submitted. Is this possible?


Solution

  • $(function(){
        $.ajaxSetup({
            beforeSend: function() {
                $('.lightbox').append('<div id="page-loader" style="display:block"><div class="page-loader-overlay"></div><div class="page-loader-content-container"><div class="top-corners"><div></div></div><div class="middle"><div class="page-loader-content">Loading...</div></div><div class="bottom-corners"><div></div></div></div></div>');
            },
            complete: function(xhr) {
                $('.lightbox#page-loader').remove()
            },  
        });
    });
    

    Please use the function ajaxsetup. When you do it this way it will be valid in all ajax functions.

    Referrer : https://api.jquery.com/jQuery.ajaxSetup/