views:

71

answers:

2

I'm having issues with XMLHttpRequest downloading progressive data. I get a state 2 and than state 3. After state 3 it never gets called again... What am I doing wrong? I read somewhere I need to flush the data but how do I do that?

Here is my code:

    var xmlHttp = new XMLHttpRequest();
    // try to connect to the server
    try
    {
      // initiate server request
      xmlHttp.open("GET", "http://208.43.121.133:8164/;", true);
      xmlHttp.setRequestHeader("Icy-Metadata", "1");
      xmlHttp.onreadystatechange = function() 
      {
          alert("status: "+xmlHttp.status);
          alert("State: "+xmlHttp.readyState);

          if (xmlHttp.readyState == 3)
        {
            alert(xmlHttp.responseText);
        }
      };
      xmlHttp.send(null);
    }
    // display an error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
A: 

The problem is most likely with this segment:

    if(xmlHttp.readyState == 3) {
        alert(xmlHttp.responseText);
    }

The reason being is that the xmlRequest isn't complete yet (readyState=4 when complete). When you requested the responseText prematurely, it triggered an error and stopped the code from finishing.

So you would change it to:

if(xmlHttp.readyState == 4) {
    alert(xmlHttp.responseText);
}
Kranu
Well the thing is, I need the data as it comes in. I can't wait till it's done since it will never be done, it's a continuous data stream.
Moto
Well that's not how you would implement a continuous data stream. What you would do is load one part, when it's done, request the next part of the stream. xmlHttp isn't for continuous data streams.
Kranu
A: 

Kranu is correct, you're not allowed to read responseText when readyState is 3. See http://www.davidflanagan.com/2005/08/xmlhttprequestreadystate-3.html

The solution is to send a message at a time. When you receive one message, just make another XHR. That's how google does (did?) server push.

Juan Mendes
Thanks for the link! More precise information... So I'm stuck :( The given url link from my sample code above is from a radio station and there is continuous data packets plus metadata... that's what I'm after, the metadata... I want to parse this data... So than Javascript does NOT provide progressive download. :(
Moto
Is the radio station within the same host? I'm guessing it is since you're making XHRs to it. The alternative is to load the url into an iframe and check the contents of the iframe at intervals. Lastly, you could write a script on the server uses regular sockets to the radion station and outputs json messages to your client.
Juan Mendes
You couldn't do it directly from javascript in any case since it's binary data that is not base64 encoded.
Juan Mendes
Thanks Juan... You kind of just dismissed the idea of using Javascript to process this data... I don't have access to running php scripts :(
Moto