Skip to content

Instantly share code, notes, and snippets.

@samarpw
Forked from ebta/index.html
Created September 22, 2023 11:33
Show Gist options
  • Save samarpw/526c332c44ddc8cd91c626e41b4aef4a to your computer and use it in GitHub Desktop.
Save samarpw/526c332c44ddc8cd91c626e41b4aef4a 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment