Created
September 10, 2019 09:33
-
-
Save ebta/cec97d2592d5dd5ddb7be07746a4b0d9 to your computer and use it in GitHub Desktop.
PHP - Flushing While Loop Data with Ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
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
Make sure in php.ini that output_buffering is set (active), for example