repeated XMLHttpRequest GETs and displaying result

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • RossGK

    repeated XMLHttpRequest GETs and displaying result

    I'm a bit new to javascript - as will be obvious below.

    I'm using an XMLHttpRequest to get a bit of data from server (django),
    and it works nicely for single events. But my eventual outcome needs
    to be a series of data transmissions. I figured requesting data over
    and over until the data is some value that triggers the stop would be
    an interesting first attempt. To move forward, I wrapped my initial
    single data request in a for-loop to see if I could do multiple calls.

    Here's my javascript stuff...

    Code:
    for (i=0;i<=5;i++) {
    xmlHttp.onreadystatechange=function()
    
    { if (xmlHttp.readyState==4)
    { document.myForm.myvar.value=xmlHttp.responseText;
    }
    }
    xmlHttp.open("GET","/ajax_data",true);
    xmlHttp.send(null);
    
    //alert("got here")
    dopause(500);        //wait 500ms
    }
    What I've noticed is that with that alert line commented out, nothing
    seems to happen -ie I don't see the data receive. I expected to see
    it flash 5 times (the server sends a random number)

    When I put the alert in, the alert does in fact pop up, and the data
    gets displayed.

    Does the alert message cause a window refresh that I need to emulate
    when the alert is not there. What do I need to do to make it cycle
    through the get 5 times and actually show me what comes up, WITHOUT
    using an alert pop!?

    Thanks for any suggestions
  • after9

    #2
    Re: repeated XMLHttpRequest GETs and displaying result

    On Jun 25, 2:44 pm, RossGK <ros...@gmail.c omwrote:
    I'm a bit new to javascript - as will be obvious below.
    >
    I'm using an XMLHttpRequest to get a bit of data from server (django),
    and it works nicely for single events.  But my eventual outcome needs
    to be a series of data transmissions.  I figured requesting data over
    and over until the data is some value that triggers the stop would be
    an interesting first attempt.  To move forward, I wrapped my initial
    single data request in a for-loop to see if I could do multiple calls.
    >
    Here's my javascript stuff...
    >
            for (i=0;i<=5;i++) {
                    xmlHttp.onready statechange=fun ction()
    >
                    { if (xmlHttp.readyS tate==4)
                            { document.myForm .myvar.value=xm lHttp.responseT ext;
                            }
                    }
                    xmlHttp.open("G ET","/ajax_data",true );
                    xmlHttp.send(nu ll);
    >
                    //alert("got here")
                    dopause(500);        //wait 500ms
              }
    >
    What I've noticed is that with that alert line commented out, nothing
    seems to happen -ie I don't see the data receive.  I expected to see
    it flash 5 times (the server sends a random number)
    >
    When I put the alert in, the alert does in fact pop up, and the data
    gets displayed.
    >
    Does the alert message cause a window refresh that I need to emulate
    when the alert is not there.  What do I need to do to make it cycle
    through the get 5 times and actually show me what comes up, WITHOUT
    using an alert pop!?
    >
    Thanks for any suggestions
    Wish I could test this, but I don't have the resources. I'm assuming
    the myvar is a text field or text area in your form? Try appending
    the responsetext to this section - not just setting it (not as a
    permanent solution, mind you, but just to debug). It may be being
    overwritten with a null response.

    Comment

    • RossGK

      #3
      Re: repeated XMLHttpRequest GETs and displaying result

      Wish I could test this, but I don't have the resources. I'm assuming
      the myvar is a text field or text area in your form?

      Yes, the text gets assigned to myvar in the form below...

      <form name="myForm">
      Stuff: <input type="text" onkeyup="getSer verData();" name="username" /
      >
      Response: <input type="text" name="myvar" />
      </form>

      .... and as I say works nicely in a single event, or with the alert
      pop.
      Try appending the responsetext to this section - not just setting it (not as a
      permanent solution, mind you, but just to debug). It may be being
      overwritten with a null response.
      Not sure what you mean... do you mean like some sort of print
      statement? (sorry my javascript weakness is showing)....


      Comment

      • after9

        #4
        Re: repeated XMLHttpRequest GETs and displaying result

        On Jun 25, 3:44 pm, RossGK <ros...@gmail.c omwrote:
        Wish I could test this, but I don't have the resources.  I'm assuming
        the myvar is a text field or text area in your form?
        >
        Yes, the text gets assigned to myvar in the form below...
        >
        <form name="myForm">
                Stuff: <input type="text" onkeyup="getSer verData();" name="username" /
        >
                Response: <input type="text" name="myvar" />
        </form>
        >
        ... and as I say works nicely in a single event, or with the alert
        pop.
        >
        Try appending the responsetext to this section - not just setting it (not as a
        permanent solution, mind you, but just to debug).  It may be being
        overwritten with a null response.
        >
        Not sure what you mean... do you mean like some sort of print
        statement?  (sorry my javascript weakness is showing)....
        Try document.myForm .myvar.value+=x mlHttp.response Text;

        instead of

        document.myForm .myvar.value=xm lHttp.responseT ext;

        Comment

        • RossGK

          #5
          Re: repeated XMLHttpRequest GETs and displaying result

          On Jun 25, 3:46 pm, after9 <ggama...@gmail .comwrote:
          >
          Try document.myForm .myvar.value+=x mlHttp.response Text;
          >
          instead of
          >
          document.myForm .myvar.value=xm lHttp.responseT ext;
          Same behaviour results. When I keep the alert box in there, I see the
          data get appended successively to the the previous data, and the form
          field fills up. Without the alert box, nothing shows up.

          Looking at my server log, interestingly I notice each time the alert
          pops up, the data is displayed and I dismiss the alert, the server
          shows that it has received a request and sent the data.

          Without the alert box, the server shows only one request (and nothing
          shows up on my page). So it seems the for-loop doesn't succeed in
          making multiple requests without the alert box.

          Will have to puzzle over that a bit longer...

          Comment

          • Tom Cole

            #6
            Re: repeated XMLHttpRequest GETs and displaying result

            On Jun 25, 4:02 pm, RossGK <ros...@gmail.c omwrote:
            On Jun 25, 3:46 pm, after9 <ggama...@gmail .comwrote:
            >
            >
            >
            Try document.myForm .myvar.value+=x mlHttp.response Text;
            >
            instead of
            >
            document.myForm .myvar.value=xm lHttp.responseT ext;
            >
            Same behaviour results. When I keep the alert box in there, I see the
            data get appended successively to the the previous data, and the form
            field fills up. Without the alert box, nothing shows up.
            >
            Looking at my server log, interestingly I notice each time the alert
            pops up, the data is displayed and I dismiss the alert, the server
            shows that it has received a request and sent the data.
            >
            Without the alert box, the server shows only one request (and nothing
            shows up on my page). So it seems the for-loop doesn't succeed in
            making multiple requests without the alert box.
            >
            Will have to puzzle over that a bit longer...
            I can't see all your code, but it appears to me that without the pause
            in there, you are reassigning the xmlhttprequest before it was
            completed. You need to launch separate instances of xmlhttprequest,
            rather than successively firing off the same one before it has
            received a response. Know what I mean?

            Comment

            • =?ISO-8859-1?Q?=22=C1lvaro_G=2E_Vicario=22?=

              #7
              Re: repeated XMLHttpRequest GETs and displaying result

              RossGK escribió:
              Code:
              	for (i=0;i<=5;i++) {
              		xmlHttp.onreadystatechange=function()
              I'm not sure about your code (that's what frameworks have, you need to
              be familiar with them) but it seems you only have one XMLHttp object and
              you are overwriting its onreadystatecha nge handler on every loop
              interation. I suppose only the last one works :-?

              If you need to perform 6 simultaneous calls you need 6 separate
              instances of your XMLHttp object type:

              Code:
              // Untested!
              function YourXMLHttpObject(){
              // ...
              this.onreadystatechange = function(){
              //...
              }
              }
              
              var calls =[];
              for(var i=0; i<6; i++){
              var xml = new YourXMLHttpObject;
              xml.foo = bar;
              //...
              calls.push(xml);
              }

              Code:
              		{ if (xmlHttp.readyState==4)
              			{ document.myForm.myvar.value=xmlHttp.responseText;
              			}
              		}
              		xmlHttp.open("GET","/ajax_data",true);
              		xmlHttp.send(null);
              
              		//alert("got here")
              		dopause(500);        //wait 500ms
              I don't know who dopause() works but, in general, I've found sleep()
              clones of little help in JavaScript development (just an opinion).



              --
              -- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
              -- Mi sitio sobre programación web: http://bits.demogracia.com
              -- Mi web de humor al baño María: http://www.demogracia.com
              --

              Comment

              • Henry

                #8
                Re: repeated XMLHttpRequest GETs and displaying result

                On Jun 26, 11:28 am, "Álvaro G. Vicario" wrote:
                RossGK escribió:
                >
                > for (i=0;i<=5;i++) {
                > xmlHttp.onready statechange=fun ction()
                >
                I'm not sure about your code (that's what frameworks have, you
                need to be familiar with them)
                ?
                but it seems you only have one XMLHttp object and
                you are overwriting its onreadystatecha nge handler on
                every loop interation. I suppose only the last one works :-?
                >
                If you need to perform 6 simultaneous calls you need 6
                separate instances of your XMLHttp object type:
                <snip>

                But making 6 simultaneous calls is not what the OP wants; it is one of
                the mistakes being made (and the HTTP limit on the number of
                simultaneous connections to the server (which is 2) would make that
                difficult to say the least (even if some browsers disregard that
                limit)). 6 calls in sequence seems to be (nearer) what is wanted,
                which implies the - onreadystatecha nge - handler arranging a
                subsequent request, for which a single XML HTTP request object would
                be sufficent.

                Comment

                • RossGK

                  #9
                  Re: repeated XMLHttpRequest GETs and displaying result

                  On Jun 25, 4:33*pm, Tom Cole <tco...@gmail.c omwrote:
                  I can't see all your code, but it appears to me that without the pause
                  in there, you are reassigning the xmlhttprequest before it was
                  completed. You need to launch separate instances of xmlhttprequest,
                  rather than successively firing off the same one before it has
                  received a response. Know what I mean?
                  Understood, but that's why I had put in a little sleep function to
                  give the request a chance to come back before firing it off again.

                  The doPause is a simple loop...

                  Code:
                  function dopause(msecs)
                  {var date = new Date();
                  var nowDate= null;
                  
                  do { nowDate= new Date(); }
                  while(nowDate-date < msecs);
                  }
                  So given that there IS a pause happenging between requests, it seems
                  like the alert box causes the equivalent of a screen 'repaint'...but
                  if that was the case I'd see the last one... and I don't. In fact,
                  the server side reports indicate only one request then a stall.

                  R.

                  Comment

                  • RossGK

                    #10
                    Re: repeated XMLHttpRequest GETs and displaying result

                    On Jun 26, 7:01 am, Henry <rcornf...@rain drop.co.ukwrote :
                    On Jun 26, 11:28 am, "Álvaro G. Vicario" wrote:
                    >
                    RossGKescribió:
                    >
                       for (i=0;i<=5;i++) {
                               xmlHttp.onready statechange=fun ction()
                    >
                    I'm not sure about your code (that's what frameworks have, you
                    need to be familiar with them)
                    >
                    ?
                    >
                    but it seems you only have one XMLHttp object and
                    you are overwriting its onreadystatecha nge handler on
                    every loop interation. I suppose only the last one works :-?
                    >
                    If you need to perform 6 simultaneous calls you need 6
                    separate instances of your XMLHttp object type:
                    >
                    <snip>
                    >
                    But making 6 simultaneous calls is not what the OP wants; it is one of
                    the mistakes being made (and the HTTP limit on the number of
                    simultaneous connections to the server (which is 2) would make that
                    difficult to say the least (even if some browsers disregard that
                    limit)). 6 calls in sequence seems to be (nearer) what is wanted,
                    which implies the - onreadystatecha nge - handler arranging a
                    subsequent request, for which a single XML HTTP request object would
                    be sufficent.
                    Thanks for that followup. I would be worried about a proliferation of
                    calls, and sequencing issues. While if I use the same one, ensuring it
                    finishes before refiring (onreadystatech ange) it seems safer, that I
                    won't have some network congestion returning request 3 after request 5
                    or something.

                    I guess the difference is that I'd like sequential calls rather than
                    simultaneous calls

                    ?


                    Comment

                    • Thomas 'PointedEars' Lahn

                      #11
                      Re: repeated XMLHttpRequest GETs and displaying result

                      RossGK wrote:
                      On Jun 25, 4:33 pm, Tom Cole <tco...@gmail.c omwrote:
                      >I can't see all your code, but it appears to me that without the pause
                      >in there, you are reassigning the xmlhttprequest before it was
                      >completed. You need to launch separate instances of xmlhttprequest,
                      >rather than successively firing off the same one before it has
                      >received a response. Know what I mean?
                      >
                      Understood, but that's why I had put in a little sleep function to
                      give the request a chance to come back before firing it off again.

                      The doPause is a simple loop...

                      Code:
                      function dopause(msecs)
                      	{var date = new Date();
                      	 var nowDate= null;
                      
                      	 do { nowDate= new Date(); }
                      	 while(nowDate-date < msecs);
                      That is probably the worst thing you can do. Especially in a
                      single-threaded environment like this.

                      As it was said before, you need to start the next request in the
                      onreadystatecha nge event listener of the previous one. Quick hack:

                      Code:
                      // add feature tests and alternatives here
                      var xhr = new XMLHttpRequest();
                      
                      // suppose you are within a block statement already;
                      // else use a function *declaration* instead
                      var f = function() {
                      if (xhr.readyState == 4)
                      {
                      if (!stopCriteria)
                      {
                      // wait for a while before the next request
                      // so we are not "hammering"; add feature tests here
                      var t = window.setTimeout(
                      function() {
                      window.clearTimeout(t);
                      t = null;
                      xhr.open("GET", "http://bar.example", true);
                      xhr.onreadystatechange = f;
                      xhr.send(...);
                      },
                      1000);
                      }
                      };
                      
                      xhr.open("GET", "http://foo.example", true);
                      xhr.onreadystatechange = f;
                      xhr.send(...);
                      I think I have posted something similar here before.


                      PointedEars
                      --
                      Anyone who slaps a 'this page is best viewed with Browser X' label on
                      a Web page appears to be yearning for the bad old days, before the Web,
                      when you had very little chance of reading a document written on another
                      computer, another word processor, or another network. -- Tim Berners-Lee

                      Comment

                      • RossGK

                        #12
                        Re: repeated XMLHttpRequest GETs and displaying result


                        Thanks for the comments. Not sure I'm any closer to my goal, but there
                        are some things to explore in the postings and in my further JS ramp up...

                        Comment

                        • Jorge

                          #13
                          Re: repeated XMLHttpRequest GETs and displaying result

                          Code:
                          <html><head><script>
                          window.onload= function () {
                          var x= function (p) { return document.getElementById(p) },
                          xmlHttp= new XMLHttpRequest();
                          xmlHttp.i= 5;
                          xmlHttp.onreadystatechange= function () {
                          if (xmlHttp.readyState === 4) {
                          x('id').innerHTML= (xmlHttp.i--)+": "+xmlHttp.responseText;
                          setTimeout(xmlHttp.doItAgain, 500);
                          }
                          };
                          (xmlHttp.doItAgain= function () {
                          if (xmlHttp.i) {
                          xmlHttp.open("GET","/ajax_data",true);
                          xmlHttp.send(null);
                          } else {
                          xmlHttp= undefined;
                          }
                          })();
                          };
                          </script></head><body><span id="id"></span></body></html>
                          On a Mac, works fine in Safari, FF2, Opera 9.5, but not in FF3 : the
                          second call to xmlHttp.send(nu ll) does nothing (!), Why ?.

                          HTH,
                          --Jorge.

                          Comment

                          • Jorge

                            #14
                            Re: repeated XMLHttpRequest GETs and displaying result

                            On Jun 27, 7:26 pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
                            wrote:
                            >
                            Once you've seen an error message popping up when navigating away or a UA
                            leaking memory because of a timeout or interval not properly cleared, you
                            will see how wrong you are here.
                            I understand the need to clear a setInterval() timer, but not a
                            setTimeout() that has already timed out.
                            In which browser/browsers did you observe those leaks and/or error
                            messages ?
                            (IE, again ?)
                            Setting "t= null" (?) is 200% useless too.
                            >
                            I will look into that later.
                            >
                            And there's no need to assign the handler "xhr.onreadysta techange = f"
                            more than once: that line could be deleted as well.
                            >
                            Obviously you don't know how XHR is implemented.
                            Nope. I don't. But if you do, may you please explain why :
                            An nsIXMLHttpReque st::send() call clears all event listeners:
                            only in FF3... ?
                            <http://www.xulplanet.c om/references/xpcomref/ifaces/nsIXMLHttpReque st...>
                            Thanks,
                            --Jorge.

                            Comment

                            • Thomas 'PointedEars' Lahn

                              #15
                              Re: repeated XMLHttpRequest GETs and displaying result

                              Jorge wrote:
                              Thomas 'PointedEars' Lahn wrote:
                              >Once you've seen an error message popping up when navigating away or a UA
                              >leaking memory because of a timeout or interval not properly cleared, you
                              >will see how wrong you are here.
                              >
                              I understand the need to clear a setInterval() timer, but not a
                              setTimeout() that has already timed out.
                              How did you get that idea?
                              In which browser/browsers did you observe those leaks and/or error
                              messages ? (IE, again ?)
                              Yes, it was IE 6 in particular.
                              >>And there's no need to assign the handler "xhr.onreadysta techange = f"
                              >>more than once: that line could be deleted as well.
                              >Obviously you don't know how XHR is implemented.
                              >
                              Nope. I don't. But if you do, may you please explain why :
                              >
                              >An nsIXMLHttpReque st::send() call clears all event listeners:
                              >
                              only in FF3... ?
                              Fx 2 exhibits the same behavior, and the Gecko source code shows why.


                              PointedEars
                              --
                              Prototype.js was written by people who don't know javascript for people
                              who don't know javascript. People who don't know javascript are not
                              the best source of advice on designing systems that use javascript.
                              -- Richard Cornford, cljs, <f806at$ail$1$8 300dec7@news.de mon.co.uk>

                              Comment

                              Working...