When utilizing AJAX XMLHttpRequest, the concatenated response text from Symfony's StreamedResponse becomes apparent

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();
    });
});

Answer №1

At this moment, the current approach may serve as a temporary fix. However, it's essential to note that each response contributes to a growing pool of data rather than maintaining a streamlined response.

For instance:

Response 1: Greetings
Response 2: Universe
Response 3: Farewell

When examining the XMLHttpRequest e.currentTarget property, the output would be:

Greetings
GreetingsUniverse
GreetingsUniverseFarewell

The content within the responseText attribute of XMLHttpRequest continuously updates with information from the server, even during an active connection. This allows the browser to perform periodic checks, such as monitoring changes in length.

While utilizing the following code for now, I am actively seeking a more effective solution which will be shared once discovered.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

What is causing the classList function to throw an error: Uncaught TypeError: Cannot read properties of undefined (reading 'classList')?

There's an error that I can't figure out: Uncaught TypeError: Cannot read properties of undefined (reading 'classList') console.log(slid[numberArray].classList) is working fine, but slid[numberArray].classList.add('active') is ...

Having trouble with uploading a file through AJAX in your WordPress website?

After spending most of the evening searching for a solution to my problem, I am aware that there are already several questions on this topic. This is my first time working on such a task. The issue I am facing involves uploading a file via AJAX in WordPre ...

Auto-populate AngularJS form using PHP array via JSON and $http

I came across a fantastic autocomplete feature in this plunker that I need to replicate using a PHP array with $http. When I tried adding an alert to check my array, it worked perfectly. However, I'm stuck on how to implement the filter in AngularJS. ...

I am interested in incorporating various forms within this code

I followed an online tutorial to create this code, and I've made some edits myself, mainly related to the buttons that display information. However, I'm still learning and struggling with adding different forms to each section. I would really app ...

There seems to be an internal server error occurring after attempting to post with a

While implementing ajax and web methods, I encountered an error message that says: post POST 500 (Internal Server Error) even though the path exists!!! This is the code I am currently using: function fnSendID() { $.ajax({ type: "PO ...

Tips for fixing the async/await problem in JavaScript

Here is the code I've been working on: let icsFileData = []; icsFileData = filterAttachmentArray.map(async(file) => { let buff = new Buffer(file.data, 'base64'); let text = buff.toString('ascii'); const data = await ical ...

Create a curve using two distinct colors in JavaScript

I am currently experimenting with a canvas and I have a specific challenge in mind. My goal is to draw an arc using two different colors, where the first half of the arc will be green and the second half red. Check out the code snippet below: // CANVAS co ...

What causes jquery to malfunction when making an ajax call?

UPDATE #2: I am experiencing a similar issue to this one, although it is not related to WP: . How can I implement this with my scripts? UPDATE: The main problem arises when the page is initially loaded, everything works smoothly and ajax is not triggered. ...

Fetch and showcase JSON information from a CodeIgniter method

Is there a way to retrieve data from a SQL database using ajax (json) with Codeigniter or PHP? I have attempted it, but the result shows up as "undefined." Here is the code snippet: My jQuery code snippet: $('[id^="menuitem_"]').on('click& ...

How to send a value to a function in Angular from a different function?

Within my Angular Typescript file, I am working with two functions named data and lists. My goal is to pass the variable windows from the function data to the function lists. However, when attempting to call the function lists, I encounter an error: Canno ...

Unable to execute jQuery on dynamically loaded AJAX page

Currently, I am utilizing jQuery to dynamically load a page via AJAX using the $.ajax method (specifically test.html). This HTML document consists of several buttons with associated animations when clicked (also utilizing jQuery). The .click() properties a ...

Struggling to incorporate a logic in ajax using Cakephp2

I have a website built on CakePHP2 and I am looking to incorporate an Ajax function that will redirect to another URL if a specific PHP condition is met. Otherwise, it should display an error dialog. The tutorials I found on Google are quite complex for me ...

New navigation menu changes as user scrolls

I'm struggling to find a way to implement a different navigation menu that appears when the user scrolls down. I'm envisioning something similar to this example: My goal is to have #small-menu replace #big-menu once the user starts scrolling. C ...

Using jQuery to dynamically insert input fields before displaying the Ajax response

As a newly initiated individual to jscript and AJAX, I must admit that this realm seems complex to me. However, I have made significant progress in just 2 days. I am currently working with a GET API that generates the AJAX output progressively using docum ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

What is the correct method for accessing an array within an object that is nested inside an array within a JSON file in Angular?

In my Angular controller code, everything is functioning properly except for the $scope.Product. I am unable to access the array of product details. Here is the relevant code snippet: .controller('aboutCtrl', function ($scope, aboutService) { ...

Managing jQuery Dependency in Node Package

I am facing an issue while trying to implement the 'jvectormap' package in Node, as it has a dependency on jQuery. My query is fairly straightforward. Whenever I attempt to import jVectorMap, I encounter the following error: Uncaught ReferenceE ...

Sending emails with Swiftmailer on a localhost server

Currently, I am attempting to send emails using Symfony SwiftMailer on my local server. I have copied and pasted the following line into my .env file : MAILER_URL=smtp://localhost:25 However, upon sending the email, I encountered the following error ...

Preventing variables from reinitializing in express.js

Within my app.js file, I invoke a search function that communicates with an LDAP server. Upon doing so, the server sends back a cookie which is essential for my subsequent queries. My intention was to save this cookie as an app.local variable in my app.j ...