Bugaboo
Bugaboo

Reputation: 971

jQuery fadeIn() not working with AJAX call

Here's my HTML code:

<div id="loading"><img src="blah blah" alt="Loading..." /></div>   

Here's my JS code:

  $(document).ready(function () {       
            $('#loading').hide();

            $("#submitSessionBtn").click(function () {
                $('#loading').fadeIn();                         
                d3.select("svg").remove();

                $.ajax({
                    type: "GET",
                    url: "Home/GetStuff/",
                    dataType: "json",
                    async: false,
                    success: function (result) {
                        console.log("Success!");
                        $('#loading').fadeOut();})

The image is basically a spinner image indicating loading. I want the image to be displayed as soon as I click the submit button and disappear when the AJAX call is done. But, currently it shows up a few seconds before the AJAX call completes and not as soon as the submit button is pressed.

What am I doing wrong?

Upvotes: 0

Views: 630

Answers (2)

Jason Nesbitt
Jason Nesbitt

Reputation: 740

The fadeIn function behaves asynchronously and the code you have immediately below the call will continue to execute before the fadeIn operation is complete. What you want to do is not run your code until it's complete. To do this, the fadeIn function (as with show, slideDown, etc) takes a function as an optional parameter that it will execute when the operation is complete. Put your ajax call inside of an anonymous function that you pass to fadeIn. It would look like this:

$('#loading').fadeIn(function(){
     $.ajax({
                    type: "GET",
                    url: "Home/GetStuff/",
                    dataType: "json",
                    async: false,
                    success: function (result) {
                        console.log("Success!");
                        $('#loading').fadeOut();})
});  

Upvotes: 1

FirebladeDan
FirebladeDan

Reputation: 1069

You do have the $(#loading') tags in the correct positions because only once the ajax call is complete will success be called. I would recommend using just show and hide. I'm sure FadeIn is introducing some gradient color between sequences so it is showing up just can't see it yet. As for disappearing to early that's because some execution is occurring. From my experience it was normal if doing database fetch or some text file reading that maybe a clean up occurred behind the scenes.

Upvotes: 0

Related Questions