Adding a loading image in jQuery ajax post

I have the following javascript to submit a form via ajax without updating the screen. Since the message takes a little time, I wanted to add a boot image during processing.

I see this article , but it looks like only a list of .load () or .get (), but not $ .post.

<script type="text/javascript"> $(document).ready(function() { $('#contact form').live('submit', function() { $.post($(this).attr('action'), $(this).serialize(), function(data) { $("#contact").replaceWith($(data)); }); return false; }); }); </script> 
+4
source share
2 answers

Just add a few calls to hide / show the loading screen / div, whatever:

 <script type="text/javascript"> $(function() { $('#contact form').live('submit', function() { $("#Loading").fadeIn(); //show when submitting $.post($(this).attr('action'), $(this).serialize(), function(data) { $("#contact").replaceWith($(data)); $("#Loading").fadeOut('fast'); //hide when data ready }); return false; }); }); </script> <div id="Loading">I'm loading, image here, whatever you want</div> 
+12
source

I inserted this so that it shows up on every ajax call, no matter what I have (I have several)

 /* show the message that data is loading on every ajax call */ var loadingMessage = 'Please wait loading data for ' + defaultPageDoctor; $(function() { $("#Errorstatus") .bind("ajaxSend", function() { $(this).text(loadingMessage); $(this).show(); }) .bind("ajaxComplete", function() { $(this).hide(); }); }); 

Just create an element with id #ErrorStatus, for example:

 <div class="newProcedureErrorStatus ajaxLoading " id="newProcedureErrorStatus"> <span id="Errorstatus" class="ui-state-error-text newProcedureErrorStatusText"></span> <span id="Errorstatus2" class="ui-state-error-text newProcedureErrorStatusText"> </span> </div> 

Now for bonus rounds you can use this area to place other messages, I also turned on the timer:

 /* show message for interval */ var saveMessageText = 'Saving...'; function ShowStatus(saveMessage, message, timeInMilliseconds) { var errorMessage = $("#Errorstatus"); if (saveMessage) { errorMessage.show(); //var myNumber = 0; var myInterval = window.setInterval(function() { message = message + '...'; errorMessage.text(message); errorMessage.show(); }, 1000); window.setTimeout(function() { clearInterval(myInterval); errorMessage.hide(); }, timeInMilliseconds); } else { errorMessage.text(message); errorMessage.show(); window.setTimeout('$("#Errorstatus").hide()', timeInMilliseconds); }; }; 

use it like this:

  ShowStatus(true, 'Save Failed with unknown Error', 4000); 
+1
source

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


All Articles