Having difficulty interpreting the responseText

Currently experimenting with

  • Redis
  • Webdis
  • Dart

Here's my code snippet

#import('dart:html');
#import('dart:json');

class ChatClient {
  XMLHttpRequest listener;
  int parsePosition = 0;

  void connect(){
    this.listener = new XMLHttpRequest();
    this.listener.open("GET", "http://i.target.co.uk:9005/subscribe/test.json", true);
    this.listener.setRequestHeader('Accept', 'application/json');
    this.listener.on.readyStateChange.add(handleData);
    this.listener.send();
  }

  void handleData(Event event){
    print(this.listener.responseText);
    /*
    if (this.listener.responseText != ""){
      Map data = JSON.parse(this.listener.responseText);
      print(data["subscribe"]);
    }
    */
  }
}

void main(){
  ChatClient client = new ChatClient();
  client.connect();
  document.query('#status').innerHTML = 'Loaded!';
}

Encountering an issue where the responseText keeps growing infinitely like

{"subscribe":["subscribe","test",1]}
{"subscribe":["subscribe","test",1]}{"subscribe":["message","test","e"]}
{"subscribe":["subscribe","test",1]}{"subscribe":["message","test","e"]}{"subscribe":["message","test","e"]}

How can I clear or flush the responseText to avoid parsing issues?

Edit: Tried iterating or tracking string length, hoping for a cleaner solution.

Edit: Output of new print statements

readyStat: 2 status: 200
{"subscribe":["subscribe","test",1]}
readyStat: 3 status: 200
{"subscribe":["subscribe","test",1]}{"subscribe":["message","test","e"]}
readyStat: 3 status: 200

Answer №1

Revision 2: Having a similar issue as the one linked in this stack overflow question regarding readyState change: Ajax readystate 3 (Chrome / IE) - Looking for further assistance.


Revision: I may have steered you in the wrong direction - The ajax request's response status indicates (3) that it is still loading/receiving the information.

Although not directly related to your inquiry, it seems to be a part of the problem.

I came across http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/ And noticed: `readyState of type unsigned short, readonly The state of the object. The attribute MUS'T be one of the following values:

0 Uninitialized
    The initial value.
1 Open
    The open() method has been successfully called.
2 Sent
    The UA successfully completed the request, but no data has yet been received.
3 Receiving
    Immediately before receiving the message body (if any). All HTTP headers have been received.
What about HEAD requests?
4 Loaded
    The data transfer has been completed.

Therefore, at stage 3, responseText contains the partial data.

Referencing :

... the URI /some/uri can establish a persistent connection, which means that unless the connection is terminated by the script or the server, readyState will always be 3 (interactive). According to the docs, I should be able grab the incomplete response from the server at this time, but apparently not ...


While browsing through msdn, I found this http://msdn.microsoft.com/en-us/library/ie/ms534361(v=vs.85).aspx:

You cannot call responseBody and responseText properties to obtain partial results (readyState = 3). Doing so will return an error, because the response is not fully received. You must wait until all data has been received.


Suggested solution:

void handleData(Event event){
  print(this.listener.responseText);

  int a = this.listener.readyState;
  int b = this.listener.status;
  print("readyStat: $a status: $b");

  if (this.listener.readyState == 4 && this.listener.status == 200) {
    if (this.listener.responseText != ""){
      Map data = JSON.parse(this.listener.responseText);
      print(data["subscribe"]);
    }
  }
}

In the receiver object, keep track of the readyState and status. When they reach a state of completion (readyState == 4 and status==200), your data might be fully available.

Please note that this code is untested due to lack of suitable testing environment.

Answer №2

Implemented the final solution.

  function establishConnection(){
    let httpRequest = new XMLHttpRequest();
    httpRequest.open("GET", "http://example.com/subscribe/data", true);
    httpRequest.setRequestHeader('Accept', 'application/json');
    httpRequest.onreadystatechange = handleResponse;
    httpRequest.send(); 
  }

  function handleResponse(event){
    try {
      let responseData = JSON.parse(httpRequest.responseText.substring(parseIndex));
      parseIndex = httpRequest.response.length;
      let receivedMessage = responseData['subscribe'][2];
      console.log("Received message: $receivedMessage");
    } catch (error){
    }
  }

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

Error: Unable to access attributes of an unknown variable (retrieving 'use')

I encountered an issue (TypeError: Cannot read properties of undefined (reading 'use')) while trying to execute the 'node server.js' command in the Terminal. The error points to my auth.routes.js file. https://i.sstatic.net/NQ5XL.png ...

Animations within Angular components are being triggered even after the parent component has been removed from

When a child component has an animation transition using query on mat-table rows, hiding the parent component will now trigger the child animation. To see this in action, check out this reproduction scenario: https://codesandbox.io/s/intelligent-jasper-hz ...

Read a local file using the HTML5 FileReader

I am currently working on developing an offline application that can read text from a locally stored text file. I have been researching and found that using html5 and FileReader can make this possible. My goal is to set a hard-coded relative path for the ...

Transforming a TypeScript enum into an array of objects

My enum is defined in this structure: export enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } However, I want to transform it into an object ar ...

Steps to incorporate this jQuery script

After receiving a solution to my problem, I'm struggling with how to actually put it into practice. $(function(){ $.get('file1.php', function(data){ $('#dropdown1').html( data ); }); // when dropdown1 is chang ...

What steps can be taken to resolve an ESLing error in this situation?

Check out this code snippet: <template v-if="isTag(field, '')"> {{ getItemValue(item, field) ? getItemValue(item, field) : '&#8211'; }} </template> An issue has been identified with the above code: Er ...

Insects featuring a button and tooltip duo creating a captivating "pull-effect"

Why is the button pulling when I move the cursor over a camera? Is there a way to solve this issue? <div class="input-group-btn advanced-group"> <button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Send Imag ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Initialization of webix combo options values in HTML code

Currently, I am working with the Webix UI framework and I am trying to achieve something similar to: <div view="combo" options="fruit"></div> This is what I have in my JavaScript file: $scope.fruit =[{id:1, value: "Apple"}, {id:2, value: "Ba ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

I am encountering an issue stating "indexRouter has not been defined"

Encountering an error "indexRouter is not defined" while attempting to run the code below. Despite attempts to remove the line, additional errors persist. Can anyone clarify the rationale behind using the common variable router for both index.js and user.j ...

Tips for transferring input field values through the href attribute in HTML?

How can I pass an integer value from a link to an input field's value? Imagine example.com is a webpage with one input field. I would like to achieve something like this: Click here 1 Click here 2 If the user clicks on click here 1, then ...

Mobile Menu in wordpress stays visible after being clicked

I recently created a one-page layout that includes some links. However, when I view the site on my smartphone and open the main menu using the button to click on a link (which scrolls within the same page), I noticed that the mobile menu remains visible a ...

What is the best way to convert a string to an integer in JavaScript while still maintaining compatibility with Internet Explorer 11?

Here is the code snippet that I am working with: setCol (param) { // missing forEach on NodeList for IE11 if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = Array.prototype.forEach; } const a ...

Arranging a JSON Object Array in JavaScript by its alphanumeric key attribute order

I need assistance sorting this JSON array by unitId var array = [ { id: 10, unitId: 'unit17' }, { id: 11, unitId: 'unit19' }, { id: 13, unitId: 'unit27' }, { id: 12, unitId: 'unit2' }, { id: 13, unitId: 'unit ...

IE encounters an absolute z-index problem when expanding concealed content

I'm having trouble with the positioning of a block (div). I am new to CSS, so any help would be greatly appreciated. Here is the code snippet: http://jsfiddle.net/9rEmt/ (please check it out) for viewing online in IE. When I use absolute for positio ...

Angular: Dynamically changing checkbox's status from parent

I'm in the process of developing a switcher component that can be reused. The key requirement is that the state of the switch should only change after an API call is made at the parent component level. If the API call is successful, then the state cha ...

What steps do I need to take to transform this click event function into one that is triggered automatically upon the div loading?

In order to automatically load content into a div using innerHTML, the PHP file must be retrieved and the div updated with its content. Within this div is another one labeled "tweet" which displays actual tweets based on a specific hashtag provided through ...

Encountering a Type Error with Webpack4 when running npm start

When I run `npm start` on my Vue project, everything seems okay, but when I open the browser page, it shows up blank and gives me an Uncaught error: TypeError: Cannot read property 'call' of undefined The console view displays the following e ...