Add effect "loading" jquery

1

I would like to add a load effect when the person submits the form, and after about 2 seconds, the load ends and the form displays the result (error or not) I would like to know how to deploy this system within this:

<script type="text/javascript"> // Script
    jQuery(document).ready(function(){
        jQuery('#ajax_form').submit(function(){
            var dados = jQuery( this ).serialize();

            jQuery.ajax({
                type: "POST",
                url: "salvaregistro.php",
                data: dados,
                success: function( data )
                {
                    $('#resultado').html(data).fadeIn("slow");
                }
            });

            return false;
        });
    });
</script>

In case #resultado is the result of the form , if it will happen or if it will give error. Would you like BEFORE it to display this result show a div hidden that has a loading image and hide it after a certain period of time?     

asked by anonymous 18.02.2015 / 13:42

3 answers

2

You can use the BlockUI plugin for this.

jQuery(document).ready(function(){
    jQuery('#ajax_form').submit(function(){
        var dados = jQuery( this ).serialize();

        $.blockUI(); //Bloquear UI
        jQuery.ajax({
            type: "POST",
            url: "salvaregistro.php",
            data: dados,
            success: function( data )
            {
                $.unblockUI(); //Desbloquear UI
                $('#resultado').html(data).fadeIn("slow");
            }
        });     
        return false;
    });
});

JSFIDDLE (Using Timeout to simulate the post)

    
18.02.2015 / 13:50
1

One of the solutions is using sonic.js ;

  

Documentation and examples:    link

How to use?

You can create a javascript function like this and add it to the .js file you prefer (remember to load together the sonic.js file) in>:

var spinnerLoading;
function getAjaxLoading() {
    if (typeof spinnerLoading === 'undefined') {
        spinnerLoading = new Sonic({
            width: 100,
            height: 100,
            stepsPerFrame: 1,
            trailLength: 1,
            pointDistance: .02,
            fps: 30,
            fillColor: '#05E2FF',
            step: function(point, index) {
                this._.beginPath();
                this._.moveTo(point.x, point.y);
                this._.arc(point.x, point.y, index * 7, 0, Math.PI*2, false);
                this._.closePath();
                this._.fill();
            },
            path: [
                ['arc', 50, 50, 30, 0, 360]
            ]
        });
    }
    spinnerLoading.play();
    return spinnerLoading.canvas;
}

Calling the spinner :

$('#resultado').html(getAjaxLoading());

You can create different spinners, it just depends on your creativity.

Then, by concluding your code, it could be + or - so (do not forget to handle the errors that can be returned from the ajax, otherwise the spinner will be spinning infinitely).

In this case the code is all together, but you can declare getAjaxLoading in a .js file that is loaded everywhere, you choose the best implementation for your case ...:

<script type="text/javascript">
    jQuery(document).ready(function() {
        var spinnerLoading;

        function getAjaxLoading() {
            if (typeof spinnerLoading === 'undefined') {
                spinnerLoading = new Sonic({
                    width: 100,
                    height: 100,
                    stepsPerFrame: 1,
                    trailLength: 1,
                    pointDistance: .02,
                    fps: 30,
                    fillColor: '#05E2FF',
                    step: function(point, index) {
                        this._.beginPath();
                        this._.moveTo(point.x, point.y);
                        this._.arc(point.x, point.y, index * 7, 0, Math.PI * 2, false);
                        this._.closePath();
                        this._.fill();
                    },
                    path: [
                        ['arc', 50, 50, 30, 0, 360]
                    ]
                });
            }
            spinnerLoading.play();
            return spinnerLoading.canvas;
        }

        jQuery('#ajax_form').submit(function(e) {

            e.preventDefault(); //Evitamos o comportamento padrão que é o submit do formulário

            var dados = jQuery(this).serialize();

            //Adicionando o LOADING
            $('#resultado').html(getAjaxLoading());


            $.ajax({
                type: "POST",
                url: "salvaregistro.php",
                dataType: "JSON",
                data: dados
            }).done(function(data) {
                $('#resultado').html(data).fadeIn("slow");
            });
        });
    });
</script>
    
18.02.2015 / 13:56
1

One solution is to create a div containing the loading image or message and leave it with visibility:hidden or display:none . In this link StackOverflow-en there is an explanation of the two properties.

Enjoying that you are using JQuery, in the documentation of the $.ajax function there are some settings that you can use to display this div only while the form is submitted. They are: beforeSend and complete .

beforeSend will be called before the request is made, so you can use it to display div "loading".

complete will be executed when the request is terminated, regardless of whether it succeeds or fails. Then you can use it to make the% of "loading" hidden again.

Example:

$(function(){
    
    var loading = $('.loading');
    
    // Supondo que seja o evento de submit
    $('#send').on('click', function(){
        
        $.ajax({
            url: 'http://pt.stackoverflow.com/',
            data: {stack:'overflow'},
            beforeSend: function(){
                loading.css('visibility', 'visible'); // exibe o div
            },
            complete: function(){
                loading.css('visibility', 'hidden'); // esconde o div
            }
        });
    });
});
/**
  O CSS não tem relevância, foi somente para tornar o
  exemplo mais "apresentável"
*/

body{ text-align: center }

#send, .loading {
    margin: 10px auto;
    width: 40%;
}

.loading > img {
    max-width: 100px
}

.loading {
    visibility: hidden
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button id='send'>Enviar</button>
<div class='loading'>
    <img src='http://i.stack.imgur.com/fLkAW.gif' alt=''/>
</div>

If you have a medium / high speed internet, you probably will not even see the image being displayed in this example I made. If possible, test in environment to simulate a real situation.

    
18.02.2015 / 17:37