Sync Ajax Download Indicator

I am using ajax with jQuery on my site and should show a progress / load indicator.

My dilemma is this:

  • Synchronous AJAX blocks the browser, so I can’t do anything (for example, show the loading indicator) until the contents are returned, and by this time it is too late.
  • I use JSON as the return type, and setting async = true returns an empty response string
  • my whole structure is based on the fact that the return type is JSON-formatted

I cannot find a way to get JS to give the user an indication that something is happening, except for the execution of alert (). (For some reason, the warning works).

Any suggestions?

My code is:

Js

var jqXHR = $.ajax( { type: "POST", url: url, cache: false, data: params, // array of parameters async: false, // responseText is empty if set to true dataType: 'json', error: function() { alert("Ajax post request to the following script failed: " + url); } } ); var html = jqXHR.responseText; 

Php

 $return = array(); $return['status'] = 1; $return['message'] = "some html here ..."; echo json_encode($return); 
+6
source share
3 answers

Before calling ajax you need to show the loading display and you can use the callback and success function to hide the loading display

  //show here the loading display $(".loading").show(); setTimeout(function() { var jqXHR = $.ajax({ type: "POST", url: url, cache: false, data: params, // array of parameters async: false, // responseText is empty if set to true dataType: 'json', error: function(){ alert("Ajax post request to the following script failed: " + url); }, success: function(){ //hide loading display here $(".loading").hide(); } }); }, 0); 

well, you need a delay using setTimeout() before calling the ajax function, because it can even stop the loading display from showing, because as soon as $(".loading").show(); animated $(".loading").show(); , ajax synchronization request will be called and, of course, will block the browser until the animation of the loading display is completed

+12
source

You can use jQuery Global Ajax event handlers. This link describes them in detail:

http://api.jquery.com/category/ajax/global-ajax-event-handlers/

 $(document).ajaxStart(function () { $("#loading").show(); }); $(document).ajaxComplete(function () { $("#loading").hide(); }); 
+9
source

Hi, use something like this to get the message in magento ....

This is html

  <div class="popupNews"> <div class="popClose">X</div> <div id="loading"><img src="<?php echo $this->getSkinUrl('images/loader.gif'); ?>" border="0" /></div> <div id="result"></div> </div> </div> 

And this is jquery

  var url = 'http://blabla.com/ajax'; jQuery.ajaxSetup({ beforeSend:function(){ jQuery("#loading").show(); }, complete:function(){ jQuery("#loading").hide(); } }); jQuery.ajax({ url: url, type: 'POST', data: {id: post}, success: function(data) { jQuery("#result").html(data); } }); 
+2
source

Source: https://habr.com/ru/post/945211/


All Articles