kilogram kilogram - 5 days ago 5
Ajax Question

I want to delay jQuery ajax successful function

I want to let user wait for 2 seconds before the HTML inside the block changes. Can you help me to set some time so that ajax request was not so fast and I had time to show some animation

I tried to set timeout but it is not working



jQuery(document).ready( function($) {

$(document).on('click', '#wp-request', function(event){
event.preventDefault();
var path = myScript.pluginsUrl + '/simple/widget-final.php';
$.ajax({
type : 'POST',
url: path,
cache: false,
success : function(data){
var newWidget = $(data);
$('#widget-container').replaceWith(newWidget);
},
error : function(){ alert('Error'); },
dataType : 'html'
});

});

$(document).on('click', '#wp-back', function(event){
event.preventDefault();
var path = myScript.pluginsUrl + '/simple/widget-initial.php';
$.ajax({
type : 'POST',
url: path,
cache: false,
success : function(data){
var newWidget = $(data);
$('#widget-container').replaceWith(newWidget);
},
error : function(){ alert('Error'); },
dataType : 'html'
});

});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="widget-container">
<p>We are on first page</p>
<a id="wp-request" href="">Send</a>
</div>




Answer

Just use setTimeout in your success callback function.

success : function(data){
    setTimeout(function(){
         var newWidget = $(data); 
         $('#widget-container').replaceWith(newWidget);
     },2000);  // The millis to wait before executing this block
},
Comments