Quiero agregar el indicador de load spinner cuando haga clic en Add y permanezca visible hasta que se complete el POST y luego reciba la alert . El elemento se agregó correctamente.
$('#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)); });Podría hacerlo simplemente poniendo su función showSpinner() (creada por usted para mostrar la rueda giratoria) antes de los comandos de fetch , y luego otra función para ocultar la rueda giratoria antes de la alerta.
Algo como eso:
$('#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)); });Para mostrar la rueda giratoria, debe usar un archivo gif para mostrar la rueda giratoria. En el siguiente código, solo necesita reemplazar el atributo src de la imagen con la ruta del gif giratorio real.
Puedes probar este código:
<!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>