Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save sohelrana820/63f029d3aa12936afbc50eb785c496c0 to your computer and use it in GitHub Desktop.
Save sohelrana820/63f029d3aa12936afbc50eb785c496c0 to your computer and use it in GitHub Desktop.
Get Streaming Data Over Jquery Ajax
<?php
/**
* Catch php output buffering data over jQuery AJAX
*
* @author: Sohel Rana (me.sohelrana@gmail.com)
* @author url: https://blog.sohelrana.me
* @link: https://blog.sohelrana.me/catch-php-output-buffering-data-jquery-ajax/
* @licence MIT
*/
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
for ($counter = 0; $counter < 10; $counter++) {
//Hard work!
sleep(1);
$processed = ($counter + 1) * 10; //Progress
$response = array('message' => $processed . '% complete. server time: ' . date("h:i:s", time()), 'progress' => $processed);
echo json_encode($response);
}
sleep(1);
$response = array('message' => 'Complete', 'progress' => 100);
echo json_encode($response);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<br/><br/><br/><br/>
<div class="col-lg-8 col-lg-offset-2">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:0">
<span id="fullResponse"></span>
</div>
</div>
<h4 id="progressTest"></h4>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
<script>
var lastResponseLength = false;
var ajaxRequest = $.ajax({
type: 'post',
url: 'catch-php-output-buffering-data-jquery-ajax.php',
data: {},
dataType: 'json',
processData: false,
xhrFields: {
// Getting on progress streaming response
onprogress: function(e)
{
var progressResponse;
var response = e.currentTarget.response;
if(lastResponseLength === false)
{
progressResponse = response;
lastResponseLength = response.length;
}
else
{
progressResponse = response.substring(lastResponseLength);
lastResponseLength = response.length;
}
var parsedResponse = JSON.parse(progressResponse);
$('#progressTest').text(progressResponse);
$('#fullResponse').text(parsedResponse.message);
$('.progress-bar').css('width', parsedResponse.progress + '%');
}
}
});
// On completed
ajaxRequest.done(function(data)
{
console.log('Complete response = ' + data);
});
// On failed
ajaxRequest.fail(function(error){
console.log('Error: ', error);
});
console.log('Request Sent');
</script>
</body>
</html>
@curry684
Copy link

Good example, thanks!

One small fix: ob_implicit_flush(true); won't work in strict mode - the parameter has to be integer 1.

@zalaks
Copy link

zalaks commented May 8, 2018

It's Not working for me. I am having foreach loop and i have used exactly what u diid in this code. :-(

My Json display like:

{"name":"test1"}{"name":"test2"}{"name":"test3"}{"message":"processover"}

Here, name object is the one that i want to show to user that your process for "test1" is done

My foreach loop:

set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
foreach ($data as $d) {
    sleep(1);
    **/* My code for storing data in database */**

$response = array('message' => **LAST_INSERTED_DATANAME**);
    echo json_encode($response);
}
sleep(1);
$response = array('message' => 'Complete');
echo json_encode($response);

@TwinMist
Copy link

TwinMist commented Mar 4, 2019

does not work for me.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 64 of the JSON data[Learn More]

any ideas?

@pervozdanniy
Copy link

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 64 of the JSON data[Learn More]

You're getting this error because of ur web server does not support streams
I've tried it on my nginx proxy and got the same error
then I tried on apache provided via xampp and everything worked well

@FluffyDiscord
Copy link

not working at all, the js call waits till php file is done and then outputs the whole data

@rs430
Copy link

rs430 commented Jun 17, 2019

not working in production server, but in wamp everything worked well,

any ideas?

@sidux
Copy link

sidux commented May 23, 2020

When using nginx you need to disable fastcgi_buffering with header('X-Accel-Buffering: no');
Disabling the cache is useful to avoid caching the response header("Cache-Control: no-cache, must-revalidate");

@PeterTough2
Copy link

Thanks a ton!

@ashleedawg
Copy link

It's Not working for me. I am having foreach loop and i have used exactly what u diid in this code. :-(

My Json display like:

{"name":"test1"}{"name":"test2"}{"name":"test3"}{"message":"processover"}

That's not valid JSON.

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