i'm working on eccomerce site and in cart.php
i want to make the qty update automatically after 5 second from stop writing
this is the java script code
<script>
function updateQty(productId) {
var qty = document.getElementById('qty-' + productId).value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('qty-' + productId).setAttribute('data-quantity', this.responseText);
}
};
xhr.open('POST', 'cart.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('obd=' + productId + '&opd=' + qty);
}
// Retrieve the quantity when needed
var quantity = document.getElementById('qty-' + productId).getAttribute('data-quantity');
</script>
i want to make it updating after 5 second of inactive or stop writing
i saw a way to do it here
but when i try it, it didn't work
// Define a timer variable to keep track of the timeout
var timer;
function updateQty(productId) {
// Clear any existing timeout when the function is called
clearTimeout(timer);
// Get the current value of the input field
var qty = document.getElementById('qty-' + productId).value;
// Send the AJAX request to the server
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var updatedQty = this.responseText;
document.getElementById('qty-' + productId).value = updatedQty;
document.getElementById('update-success-msg').style.display = 'block';
setTimeout(function() {
document.getElementById('update-success-msg').style.display = 'none';
}, 3000);
}
};
xhr.open('POST', 'cart.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('obd=' + productId + '&opd=' + qty);
// Set a new timeout to update the quantity after 5 seconds
timer = setTimeout(function() {
var newQty = document.getElementById('qty-' + productId).getAttribute('data-quantity');
if (qty != newQty) {
updateQty(productId);
}
}, 5000);
}
// Retrieve the quantity when needed
var quantity = document.getElementById('qty-' + productId).getAttribute('data-quantity');