I am using Stripe API to return the balance/credit for a given customer on their dashboard, although the API takes a long time to run and the page loading time is suffering, annoying for just a single number. I specifically didn't want to save the balance to the database, so I looked at alternatives.
I have written the PHP API call to return the balance to a new file which I was calling using setInterval
function and then updating the Div to display the balance, this works fine, although I do not want this function repeating at all, just looking for it to load and update once. I have added a preloader and ideally would like the preloader to display until such time as the balance has updated. Obviously I can't do this with setInterval
. I have tried using some of the Javascript functions I know of such as window onl oad, but this doesn't update the balance at all?
I know this function isn't the option I need for this, although I know very little Javascript and any help or recommendations would be really appreciated. Here is what I currently have:
<script>
setInterval(function() {
$("#balance").load('stripebalance.php);
}, 10000);
</script>
<div id="preloader">
<div id="loader"></div>
</div>
<div id="balance">
<h1>£-</h1>
</div>
<script>
$(window).on('load', function(){
setTimeout(removeLoader, 2000);
});
function removeLoader(){
$("#preloader").fadeOut(500, function() {
$("#preloader").remove();
});
}
</script>
CodePudding user response:
Sounds to me like you'd just like to remove the pre-loader once you've loaded the data.
jQuery's .load() function supports a callback function to execute once the request completes
jQuery(function($) {
$("#balance").load("stripebalance.php", function() {
$("#preloader").fadeOut();
});
});
There's no need for any intervals or timeouts in this.
Also, it's almost 2023 and you certainly don't need jQuery for this
const getStripeBalance = async () => {
const res = await fetch("stripebalance.php");
if (!res.ok) {
throw new Error(`Fetch error: ${res.status} - ${res.statusText}`);
}
return res.text();
}
const stripeBalanceHtmlPromise = getStripeBalance();
document.addEventListener("DOMContentLoaded", async () => {
const balance = document.getElementById("balance");
const loader = document.getElementById("preloader");
const stripeBalanceHtml = await stripeBalanceHtmlPromise;
balance.innerHTML = stripeBalanceHtml;
loader.addEventListener("animationend", () => {
loader.remove();
});
loader.classList.add("fadeOut");
});
.fadeOut {
animation: fadeOut 0.5s linear forwards;
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}