I have the controller below which returns Line 1
(as response) as soon as the endpoint is called. Two seconds later it returns Line 2
. This is fine when I directly access URL http://ajax.dev/app_dev.php/v2
so this proves that the endpoint 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;
}
When I use AJAX to call the same endpoint, the first response is fine which is response: "Line 1"
. However, the second one is response: "Line 1Line2"
so it is combined. What should I do in order to get response: "Line2"
as the second response? 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();
});
});