Below is the code for a controller that returns Line 1
as soon as the endpoint is called and then two seconds later it returns Line 2
. When accessing the URL directly at http://ajax.dev/app_dev.php/v2
, everything works 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;
}
However, when using AJAX to call the same endpoint, the second response combines both Line 1
and Line 2
into one. How can I modify this to get only response: "Line 2"
as the second response? See console log below for more information.
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 code being used.
$(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();
});
});