ClanKiller.com
http://forums.clankiller.com/

reusing xmlhttprequest objects in IE
http://forums.clankiller.com/viewtopic.php?f=24&t=3234
Page 1 of 1

Author:  Satis [ Tue Sep 01, 2009 12:46 pm ]
Post subject:  reusing xmlhttprequest objects in IE

Ok, just ran into this so I thought I'd jot it down.

Basically, I have some ajax code I threw together to be able to reuse xmlhttprequest objects. That way I'm not constantly creating new ones and chewing up memory/time.

I built most of this in FF and it worked great, since I can use firebug to debug js issues. Tested it in IE7 and the first request worked... then the second request did nothing. I debugged it pretty heavily and found I was sending the ajax request on the second attempt, but the onreadystatechange event handler was never firing. I was very, very confused.

I did learn some neat things in the process, but it turns out in IE you need to define your onreadystatechange event handler AFTER you call the XMLHttpRequest.open method. For other reason, you also have to define it before you call the XMLHttpRequest.send method. My problem is I was defining the even handler before the open.

In the end I ended up with code similar to this (trimmed for brevity)

Code:
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
   try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }
}
if(!xmlhttp)
   return false;
xmlhttp.open('POST', that.page, true);
xmlhttp.onreadystatechange = function(){
   if(xmlhttp.readyState == 4){
      if(xmlhttp.status == 500){
         that.showError('Internal Server Error');
         return;
      }
      try{ var result = xmlhttp.responseXML; }
      catch(e){   that.showError('Result not readable', result);   that.processing = false; return;}
      try{ var errors = result.getElementsByTagName('error');}
      catch(e){   that.processing = false; return; }
      if(errors.length > 0){
         var error = '';
         for(i=0; i<errors.length; i++){ error += errors.item(i).firstChild.nodeValue + '<br>';   }
         that.showError(error, result);
         that.processing = false;
         return;
      }
      try{ var response = result.getElementsByTagName('responseBlock'); }
      catch(e){   that.showError('AJAX response tag missing or unreadable'); that.processing = false; return; }
      ajaxResponse(response);
      xmlhttp.readyState = 0;
   }
}
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", vars.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(vars);   

Author:  Satis [ Tue Sep 01, 2009 12:49 pm ]
Post subject: 

for more information, check the bottom of this page:

http://en.wikibooks.org/wiki/XMLHttpRequest

Page 1 of 1 All times are UTC - 6 hours
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/