Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3918

return json from streamed response symfony

$
0
0

I have a streamed response function in my controller as below

/** * @Route("/manage/testajax", name="app_testajax") */public function testAjax(Request $request)  : Response{    if (!$request->isXmlHttpRequest()) {        throw new BadRequestHttpException('AJAX request expected.');    }    $response = new StreamedResponse();    $response->setCallback(function () {        $repeat = 4;        for ($i = 1; $i < $repeat; ++$i) {            echo 'Line '.$i;            //new JsonResponse(['message' => $i, 'status' => 'success']);            ob_flush();            flush();            if ($i < ($repeat - 1)) {                sleep(2);            }        }    });    return $response;}

and my xml request as

function startStreaming(lastResponseLength) {                xhr = new XMLHttpRequest();                xhr.open('GET', '{{ (path('app_testajax')) }}', true);                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');                xhr.onprogress = function(e) {                                       console.log(e);                    var response = e.currentTarget.response;                    var output = lastResponseLength === false                        ? response                        : response.substring(lastResponseLength);                    lastResponseLength = response.length;                     console.log(output);                };                xhr.onreadystatechange = function() {                    if (xhr.readyState == 4) {                      console.log("Completed");                        //$('#stream-output').append('<p>Completed!</p>');                    }                };                xhr.send();            }

which gives console output as

Line1 Line2 Line3 Completed

But instead i need to return a json .like

new JsonResponse(['message' => $i, 'status' => 'success']);

Is that possible.Hope Someone could help


Viewing all articles
Browse latest Browse all 3918

Trending Articles