-
-
Save samarpw/526c332c44ddc8cd91c626e41b4aef4a to your computer and use it in GitHub Desktop.
PHP - Flushing While Loop Data with Ajax
This file contains hidden or 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 hidden or 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment