Add jquery "loading" effect

Asked

Viewed 11,171 times

1

I would like to add a loading effect when the person submits the form, and after about 2 seconds, the upload 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 the #resultado is the result of the form, if it will pass or if it will fail. It would have as BEFORE that it display this result show a div hidden that has an image of loading and hide her after a certain period of time?

  • Can the loading be inside the result div and after that delete? I know a javascript api that creates "spinners", very interesting by the way.

  • I don’t know how it looks better. I thought of a div just for the 'load' that opens and closes before the result. But if it works within the result div itself has no problem

  • This question is solved?

  • Yes, but I used a different method than the answers

3 answers

2

You can use the plugin Blockui 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)

  • The problem is that I already have a div for 'loading'. Would there be no way to apply the little instead of the one that covers the whole screen? : x

  • you can use an element of the page itself as a message, look at this updated jsFiddle: http://jsfiddle.net/7eq4q4ro/1/

  • Yes only it opens in full screen. I was thinking of a more discrete div as just a phrase "loading" before you enter the reultado you understand? xD

  • this div will appear on what part of the screen? in the center of the browser? in the center of the form? what will be blocked? in this case it is interesting that you Edit your message with the HTML snippet that will be affected and the behavior you expect.

  • It is a div that appears in the form when you send it xD

  • Would that be? http://jsfiddle.net/6wo8mdmp/

  • Yes! Only with the fadein effect to enter, fadeout to exit and the result appears after exiting the loading

  • In this case just replace removeClass with fadein and addClass with fadeout.

Show 3 more comments

1

One of the solutions is using the Sonic.js;

Documentation and examples: https://github.com/padolsey/sonic.js/blob/master/README.md

How to use?

You can create a javascript function this way and add it to the file . js you prefer (remember to carry along with the file Sonic.js):

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, just depends on your creativity.

So completing your code could get + or - like this (do not forget to deal with errors that can return from ajax, otherwise the spinner will be there running endlessly).

In this case the code is all together, but you can declare getAjaxLoading in a file. js that is loaded everywhere, you choose the best implementation form 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>
  • I just didn’t understand how to apply this code.. I called Sonic.js in the form and replaced the old one with this one but nothing happens it just updates the page. Nor does the result appear

  • I’ll edit the code to see if it improves @Guilherme

  • Man, I did something wrong. Because I can’t make it work o.o. When I load Sonic.js and apply this code that you put together when I try to send the form the page updates and nothing happens.

  • @Guilherme ah already understood, you need to change a little its function, I will update and comment the change..., pronto... I added the e.preventDefault(); which in this case avoids the default behavior of Submit, which is the sending of the page... so ajax takes care of this part;

  • Ok, now the page does not update, but nothing happens when sending the heheh form

  • @William your save page.php is returning something? echo $result, for example? remove the false Return from the end .... , try debugging with console.log(), see if there is an error appearing on your browser console...

Show 1 more comment

1

One solution is you create a div containing the image or message by loading and leaving it with visibility:hidden or display:none. In that link Stackoverflow-en there is an explanation about the two properties.

Taking advantage that you are using Jquery, in documentation of function $.ajax there are some settings you can use to show this div only while the form is sent. They are: beforeSend and complete.

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

complete will be executed when the request ends, regardless of whether it is successful or error. Then you can use it to make the div of "loading" hidden again.

Example:

$(function(){
    
    var loading = $('.loading');
    
    // Supondo que seja o evento de submit
    $('#send').on('click', function(){
        
        $.ajax({
            url: '/',
            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 won’t even see the image being displayed in this example I did. If possible, test the environment to simulate a real situation.

  • Dude this code seems to be working perfectly and the way I was looking for it! But I have some questions while he: Can you define a time that the div loading becomes active? And how do I display the div result after exiting the upload?

  • @Guilherme have, has. But you want to show the loading even without sending/receiving anything? The return you can do as shown in your code, using success.

  • Yes! We say that the part of the shipment is just to make it really beautiful understand? do not need to circulate information. The important thing is that after the load disappears, the answer of the :D form appears

  • So why are you using ajax? Just create a function with interval. I thought the question was another... @Guilherme

  • I use ajax for form information to appear without the page having to be reloaded

Browser other questions tagged

You are not signed in. Login or sign up in order to post.