I am making a Testimonial rotator with Jquery for my website, but the Ajax function runs too early, so you see the HTML change, then it fades out, and back in. I’ve tried to figure out the problem, but I can’t seem to find it.
<div class="testimonials">
<div id="testimonial"></div>
</div>
<script type="text/javascript">
function loadTestimonial(){
$("#testimonial").fadeOut(1000);
$.ajax({
url: "r/get_testimonial.php",
cache: false,
async: false,
timeout: 1000,
success: function(html){
$("#testimonial").html(html);
},
});
setTimeout($("#testimonial").fadeIn(1000), 2000);
}
$(document).ready(function(){
loadTestimonial();
setInterval (loadTestimonial, 5000)
});
</script>
Try this code:
What went wrong with your code? The ajax code was called imidiatly which will replace the old HTML when it is ready, what I do above is wait for the callback of the
fadeOut()and then trigger the Ajax function. Which will get the source andfadeInthe new HTML.You might think it’s an sync function (because the Ajax had
async: false), but the jQueryfadeOutis also async, so you can not wait for that the way you did.