Search code examples
jqueryjsonajaxwebmethod

loading image displays even before submit button is clicked. Why?


We will like to display gif loading messageas soon as submit button is clicked and then disappear as soon as data is finished loading.

It is not working out very well so far.

As soon as page loads but before submit button is clicked, gif loader is displayed and stays displayed even data is finished loading.

How do I resolve this?

   $("#btnSubmit").click(function (event) {
      event.preventDefault();
     if (confirm('Please verify that your information is correct before submitting.')) {
    var empComplete = false, sourceComplete = false, spouseComplete = false, dividentComplete = false, reimbursedComplete = false, honorariaComplete = false, giftComplete = false, orgComplete = false, creditorComplete = false;
    function checkComplete() {
     if (empComplete && sourceComplete && spouseComplete && dividentComplete && reimbursedComplete && honorariaComplete && giftComplete && orgComplete && creditorComplete) {
    $("#result").text("Thank you! You have successfully completed this form");
     }
    }

//Loading message handler
    var $loading = $('#loadingDiv').hide();
    $(document)
    .ajaxStart(function () {
    $loading.show();
    })
    .ajaxStop(function () {
    $loading.hide();
    });

    $("#result").text("");
    var data = JSON.stringify(getAllEmpData());
    console.log(data);
    $.ajax({
    url: 'disclosures.aspx/SaveEmpData',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ 'empdata': data }),
    async: false,
    success: function () {
    empComplete = true;
    checkComplete();
    },
    error: function () {
    alert("Error while inserting data");
    }
    });
    }
    )};
    ...
    ...
    </script>

    //Markup

     <input type="submit" id="btnSubmit" class="btn btn-primary btn-md pull-center btn-sm" value="Submit" /><img id="loadingDiv" src="images/ajax-loader.gif" alt="Loading..." />
    <output id="result" style="margin-bottom:300px;margin-left:250px;color:#3c890e;font-weight:bold;font-size:18px;"></output>

Solution

  • Just put 'display: none;' to the img to begin with:

    <img id="loadingDiv" style="display:none;" src="images/ajax-loader.gif" alt="Loading..." />
    

    or hide it on document ready.

    Also to hide the loading gif, hide it in your success and error function or in 'complete'.

    ajaxStop checks for all ajax requests on the page not just the one you are making, from jQuery docs: Register a handler to be called when all Ajax requests have completed.

    Also do not use your $loadingDiv variable inside the 'success' or 'error' or 'complete' functions they are asynchronous and the variable will be out of scope unless you pass it in. Just select the div with jquery again.