Skip to content

Instantly share code, notes, and snippets.

@ebta
Created September 10, 2019 09:33
Show Gist options
  • Save ebta/cec97d2592d5dd5ddb7be07746a4b0d9 to your computer and use it in GitHub Desktop.
Save ebta/cec97d2592d5dd5ddb7be07746a4b0d9 to your computer and use it in GitHub Desktop.
PHP - Flushing While Loop Data with Ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
Loop through Ajax
<button onclick="doLoop()">Run</button>
<span id="info"></span>
</body>
<script>
function doLoop() {
var resp, arrs, info = document.getElementById('info');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'loop.php', true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.status == 200) {
resp = xhr.response;
arrs = resp.split('|');
if (xhr.readyState == XMLHttpRequest.LOADING) {
// console.log(resp);
info.innerHTML = arrs[arrs.length - 1];
}
// All request COMPLETE (FINISH/DONE)
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(resp);
info.innerHTML = arrs[arrs.length - 1];
}
}
}
}
</script>
</html>
<?php
header('Content-Type: text/html; charset=UTF-8');
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i < 100; $i++) {
echo '|' . str_pad($i,3,'0',STR_PAD_LEFT);
ob_flush();
flush();
usleep(100000); // 0.1s
}
echo "|SELESAI";
ob_end_flush();
@DStruecker
Copy link

Hello Ebta,
thx for your reply. I tried many options with output_buffering and other things, nothing worked. At last, I assume my firewall or virus scanner operated by our corporate IT blocks the communication. On a linux system with the webserver and client running on the same machine (as intended on the target system) it runs fine!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment