Symfony StreamedResponse response body is merged when using AJAX XMLHttpRequest
I have a controller below which it returns Line 1
(as a response) as soon as the endpoint is called. After two seconds, it returns Line 2
. It's okay when I access the URL directly http://ajax.dev/app_dev.php/v2
, so this proves that the endpoint is working as expected.
/**
* @Method({"GET"})
* @Route("/v2", name="default_v2")
*
* @return Response
*/
public function v2Action()
{
$response = new StreamedResponse();
$response->setCallback(function () {
echo 'Line 1';
ob_flush();
flush();
sleep(2);
echo 'Line 2';
ob_flush();
flush();
});
return $response;
}
When I use AJAX to call the same endpoint, the first answer is fine as it is response: "Line 1"
. However the second is response: "Line 1Line2"
, so it is combined. What should I do to get the response: "Line2"
second answer? See Console Log below.
XMLHttpRequest { onreadystatechange: xhr.onreadystatechange(), readyState: 3,
timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "http://ajax.dev/app_dev.php/v2", status: 200,
statusText: "OK", responseType: "", response: "Line 1" }
XMLHttpRequest { onreadystatechange: xhr.onreadystatechange(), readyState: 3,
timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload,
responseURL: "http://ajax.dev/app_dev.php/v2", status: 200,
statusText: "OK", responseType: "", response: "Line 1Line2" }
Complete
This is the AJAX I am using.
$(document).ready(function () {
$('button').click(function () {
xhr = new XMLHttpRequest();
xhr.open("GET", 'http://ajax.dev/app_dev.php/v2', true);
xhr.onprogress = function(e) {
console.log(e.currentTarget);
};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log("Complete");
}
};
xhr.send();
});
});
source to share
This may only be a temporary solution, because each answer is added and becomes a massive answer, not a pure answer.
eg.
Response 1: Hello
Response 2: World
Response 3: Bye
The XMLHttpRequest property e.currentTarget
will contain:
Hello
HelloWorld
HelloWorldBye
For now I will use the code below, but if I can find a better solution, I will post it.
<script>
$(document).ready(function () {
$('button').click(function () {
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://ajax.dev/app_dev.php/v2', true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onprogress = function(e) {
var response = e.currentTarget.response;
var output = typeof lastResponseLength === typeof undefined
? response
: response.substring(lastResponseLength);
lastResponseLength = response.length;
console.log(output);
};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('Complete');
}
};
xhr.send();
});
});
</script>
source to share