3

I'm trying to add a ajax loading image to a div container while the ajax request would be executed.

My Jquery code looks like the following:

<script type="text/javascript">
    $(document).ready(function(){
        $("#store, #gender, #username").change(function () {
            var store = $("#store").val();
            var gender = $("#gender").val();
            var receiver = $("#username").val();

            $.ajax({
                type: "POST",
                data: {
                    "store" : store,
                    "gender" : gender,
                    "receiver" : receiver
                },
                url: "handling/ajax/store_items_ajax.php",
                success: function(data){
                    $("#result").html(data);
                }
            });
        });
    });
</script>

How would I add a loading image to the following html div:

<div id="result" class="col-md-12"></div>

Does anyone know this?

pr0b
  • 377
  • 2
  • 3
  • 14
  • Possible duplicate of [Jquery Ajax Loading image](http://stackoverflow.com/questions/8761713/jquery-ajax-loading-image) – gre_gor Aug 23 '16 at 16:24

1 Answers1

5

Logic

- Create progress div element
<div id="progress">
    <img style="width:100%" src="/images/spinner.gif"/>
</div>

- By default hide this progress div
- Show when passing ajax request
- Hide when you get ajax response

Script

<script type="text/javascript">

    $(document).ready(function() {

      $("#store, #gender, #username").change(function () {
        var store = $("#store").val();
        var gender = $("#gender").val();
        var receiver = $("#username").val();

        $('#progress').show(); //show progress bar

        $.ajax({
            type: "POST",
            data: {
              "store" : store,
              "gender" : gender,
              "receiver" : receiver
            },
            url: "handling/ajax/store_items_ajax.php",
            success: function(data){
              $('#progress').hide(); //hide progress bar
              $("#result").html(data);
            }
        });
      });

    });

</script>
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46
  • 1
    i would hide the div on the complete event instead of succes. – edbird88 Aug 23 '16 at 15:49
  • Whichever way you need but this is robust, i have implemented this in live site and works like a charm! Please understand if you put outside then DOM will execute directly without waiting for it so may be better around AJAX request/response. Anyhow, you can play around it because you have a solution now. – Jitesh Sojitra Aug 23 '16 at 15:54
  • 1
    you could also setup a global .ajaxStart() and save some extra lines in each of your calls. https://api.jquery.com/ajaxStart/ – DevlshOne Aug 23 '16 at 17:00