Below is a simple generic implementation of a polling mechanism in Javascript, working with variable endpoint, intervals, durations, and callback.
The assumption is that you remove the while loop from the PHP code, and make sure you send back a valid JSON response. In the callback parameter I've given below the assumption is that PHP sends back json_encode(['paid' => true])
.
// interval & duration in seconds
function poll(endpoint, interval, duration, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint);
xhr.onload = function() {
var message;
try {
message = JSON.parse(xhr.response);
} catch(err) {
// malformed json
}
if (duration >= 0 && callback(message) !== false) {
setTimeout(function() {
poll(interval, duration - interval, callback);
}, interval * 1000);
}
};
xhr.send();
}
// usage
var endpoint = '/your-validity-check.php',
interval = 10, // every 10 seconds
duration = 5 * 60, // for 5 minutes
callback = function(response) {
var date = new Date();
console.log(response.paid);
// return false to abort the polling when we know the purchase is paid
if (response.paid) {
window.alert('Thank you for your purchase!');
return false;
}
};
poll(endpoint, interval, duration, callback);
NB: XHR = XMLHttpRequest; what @Giacomo shows is not long-polling, long-polling is a client-server technique which involves keeping connection requests open.