I want to add load spinner when click on Add And remain visible until the completion of POST then get alert Item has been added successfully.
$('#add').click(function() {
fetch("url")
.then(response => response.json())
.then(result => setTimeout(function(){
location.reload(alert("Item has been added successfully"));
},1250))
.catch(error => console.log('error', error));
});
You could do it simply by putting your showSpinner() function (created by you to show the spinner) before the fetch commands, and then another function to hide the spinner before the alert.
Something like that:
$('#add').click(function() {
showSpinner();
fetch("url")
.then(response => response.json())
.then(result => setTimeout(function(){
hideSpinner();
location.reload(alert("Item has been added successfully"));
},1250))
.catch(error => console.log('error', error));
});
To display the spinner, you need to use a gif file for display spinner. In the below code you just need to replace the image src attribute with the actual spinner gif path.
You can try this code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#add').click(function() {
// Show Spinner
$('<span class="spinner-section"><img src="add gif path here" alt="Please wait..." width="30px" /></span>').insertAfter($(this));
fetch('https://www.w3schools.com/jquery/')
.then(response => response.json()).then(result => setTimeout(function(){
// Remove Spinner
$('.spinner-section').remove();
location.reload(alert("Item has been added successfully"));
},1250))
.catch(error => console.log('error', error));
});
});
</script>
</head>
<body>
<button id="add">Test Button</button>
</body>
</html>