show html element before sending ajax sync request


Tags: javascript,jquery,html,css,ajax

Problem :

I want to show <div> on click by submit before sending $.ajax()

my html

<div id="waiting_div"></div>

css

#waiting_div {
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    background-color: rgba(0, 0, 0, .8);
    z-index: 999;
    display: block;
}

js functions

jQuery(document).ready(function() {
    jQuery("#waiting_div").hide();
});

function set_response_waiting() {
    jQuery("#waiting_div").show();
}
function del_response_waiting() {
    jQuery("#waiting_div").hide();
}

and main js

jQuery("#save_changed_prices").click(function(){
    set_response_waiting(); <-- showing div here

    var len = window.prices.length; //array with data for sending
    var i = 0;

    for (i = 0; i < len; i++) {
        if (window.prices[i].price >= 0) {
            jQuery.ajax({
                type: 'POST',
                url: ajaxurl,
                data: {...... },
                async: false
            }).done(function (data) {
                ...
            }).fail(function () {
                ...
            }).always(function () { 
                ...
            });
        }
    }

    del_response_waiting(); <-- hiding div
});

But set_response_waiting() function doesn't show me my "#waiting_div" before sending.

I need to redraw or update the DOM tree before sending. But how?

This don't work too..

jQuery.ajax({
                        type: 'POST',
                        url: ajaxurl,
                        data: {
                            'action': 'update_price',
                            'car_id': car_id,
                            'dep_city_id': window.prices[i].dep,
                            'arr_city_id': window.prices[i].arr,
                            'price': window.prices[i].price
                        }, 
                        beforeSend: set_response_waiting(),
                        async: false
                        })


Solution :

Use, Promise.

jQuery ajax is aync method. so your function show and immediately hide.

 jQuery("#save_changed_prices").click(function(){
        set_response_waiting(); <-- showing div here

        var len = window.prices.length; //array with data for sending
        var i = 0;
        var deferreds = [];

        for (i = 0; i < len; i++) {
            if (window.prices[i].price >= 0) {
                deferreds.push(
                    jQuery.ajax({
                        type: 'POST',
                        url: ajaxurl,
                        data: {...... },
                        async: false
                    }).done(
                        function (data) {
                           ...
                        }
                    ).fail(function () {
                            ...
                        }
                    ).always(function () { ...
                        });
                );
            }
        }
        // pending until all ajax requests done.
        $.when.apply(null, deferreds).done(function() {
            del_response_waiting(); <-- hiding div
        });
  });

--- EDIT

 jQuery("#save_changed_prices").click(function(){
        set_response_waiting(); <-- showing div here

        var len = window.prices.length; //array with data for sending
        var i = 0;
        var deferreds = [];

        for (i = 0; i < len; i++) {
            var deferred = $.Deferred();
            deferreds.push(deferred.promise());

            if (window.prices[i].price >= 0) {
                jQuery.ajax({
                    type: 'POST',
                    url: ajaxurl,
                    data: {...... },
                    async: false
                }).done(
                    function (data) {
                       ...
                    }
                ).fail(function () {
                        ...
                    }
                ).always(function () {
                        deferred.resolve(); // Resolve here!
                        ...
                    });
                );
            }
        }
        // pending until all ajax requests done.
        $.when.apply(null, deferreds).done(function() {
            del_response_waiting(); <-- hiding div
        });
  });

---- EDIT (last)

jQuery("#save_changed_prices").click(function(){
    var send_price = function() {
      var deferreds = [];

      var len = window.prices.length; //array with data for sending
      var i = 0;
      for (i = 0; i < len; i++) {
          if (window.prices[i].price >= 0) {
              deferreds.push(
                jQuery.ajax({
                    type: 'POST',
                    url: 'http://jsonplaceholder.typicode.com/posts',
                    data: { price : window.prices[i].price },
                    async: false
                }).done(function (data) {
                    console.log('done', data);
                }).fail(function () {
                    console.error(done, data);
                }).always(function () { 

                })
              );
          }
      }
      $.when.apply(null, deferreds).done(function() {
          del_response_waiting();
      });

    }
    set_response_waiting();
    setTimeout(send_price); // setTimeout for browser redraw screen!!

});

Check jsfiddle for working example. :)

https://jsfiddle.net/yourimiyi/rsu4vo3m/


    CSS Howto..

    how do i change button/image onclick to active state?

    CSS: how to place controls at both extrems of a cell table

    How to keep an element :active even after clicking

    How to show a node in a block in drupal 7

    How do i make the header/footer extend width-wise to fit the screen, and the main content extend height-wise to fit the screen?

    How I write a:hover::before in less file?

    How to make child div scrollable when it exceeds parent height?

    How may I stack multiple html/css buttons vertically along the center of the page?

    How to create a panel tab?

    How to show the text overflow after showing two lines in the div using css?

    How do I add a transition to this rollover?

    How can i refer to all of my tags in CSS?

    How to parameterize CSS selectors? [duplicate]

    How to set a spinner into the middle of the screen with CSS?

    How to assign speed parameter to callback functions

    how to dynamically change the property of css using jquery

    How to use modernizr for border-image

    How do I add box shadows when the parent div has a background image?

    How to keep div visible when hovering another div

    How do i hide html until its processed with javascript?

    Trade off for CSS sprites: how many images to combine into one

    How to set the styles on “*” and pseudo states with JavaScript? [closed]

    JavaScript CSS how to add and remove multiple CSS classes to an element

    How to copy the html contents of one iframe to another iframe including CSS?

    CSS: How to move hint box (a:hover) to the left?

    How to keep a floating div centered on window resize (jQuery/CSS)

    CSS: How do I 'raise' the last photo in this page?

    How to create this border styles in HTML/CSS? [closed]

    How to edit rails app in production env, specifically CSS

    Integration of CSS, Javascript and html ,,,howto