I encountered a peculiar issue where I am trying to display a loading spinner icon while making an AJAX request. Strangely, the spinner does not appear for the first request (such as after manually refreshing the page) but shows up for all subsequent requests. This happens when the spinner GIF is loaded from a local directory.
Interestingly, when I use this URL (https://i.sstatic.net/FhHRx.gif) that I found on another Stack Overflow post, it works consistently. However, for other URLs sourced from the web or local files, the image fails to show up on the initial request despite the AJAX call being executed (indicated by a change in screen color through styling). Any insights on why this might be happening? Below is the pertinent code snippet.
body
<body>
...
<div class="modal" name="modal" id="modal"></div>
</body>
script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document)
.ajaxStart(function () {
$("#modal").show();
})
.ajaxStop(function () {
$("#modal").hide();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Submit Data
$(".submit").click(function (e) {
e.preventDefault();
// get data ...
$.ajax({
url:url,
method:'POST',
data:{
// data values
},
success:function(response){
// update cart and some other stuff
},
});
});
});
</script>
CSS
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url('../images/ajax-loader.gif')
50% 50%
no-repeat;
}
body.loading .modal {
overflow: hidden;
}
body.loading .modal {
display: block;
}