Using beforeSend and complete in every instance of ajaxForm globally

24
October 22, 2019, at 6:40 PM

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?

Answer 1

If anyone runs across a similar dilemma, this is what I came up with and it seems to do the trick. I haven't found any problems with this thus far.

// add loading masks on form submits
$( document ).ajaxSend(function() {
    $('.lightbox').append('<div id="page-loader" style="display:block; z-index: 999"><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>');
});
$(document).ajaxSuccess(function() {
    $('#page-loader').remove()
});
Answer 2
$(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/

READ ALSO
Convert a SQL query to Laravel Eloquent

Convert a SQL query to Laravel Eloquent

I'm trying to achieve something like the following:

42
Does jquery success function assume status code 200?

Does jquery success function assume status code 200?

In an ajax success function, is it assumed the status code is 200? or could it be successful if you return 304 or 503?

28
How to optimize &ldquo;ScrollMagic+TweenMax+GSAP&rdquo; performance?

How to optimize “ScrollMagic+TweenMax+GSAP” performance?

At first sight an easy animation causes lags and is choppy on mobile devicesIt looks quite normal on PC resolution, but not on mobile

22