Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-14-2012, 04:43 PM   PM User | #1
user6110
New to the CF scene

 
Join Date: Mar 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
user6110 is an unknown quantity at this point
Overriding XMLHttpRequest

Hi,

I'm trying to get the following code to work. I'm intercepting all Ajax requests and responses by overriding XMLHttpRequest functions. The requests are alerted and sent correctly.

I also get an alert box for responses, but after that I get an error "this.orsc is not a function", and the response is not delivered correctly. Any idea what the problem is?

Code:
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(data) { alert("sent: " + data); if(this.onreadystatechange) { this.orsc = this.onreadystatechange; } this.onreadystatechange = newORSC; this.realSend(data); };
var newORSC = function() { if (this.readyState == 4) { alert("response: " + this.responseText); } this.orsc(); };
XMLHttpRequest.prototype.send = newSend;
user6110 is offline   Reply With Quote
Old 03-14-2012, 09:27 PM   PM User | #2
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 531 Times in 525 Posts
devnull69 will become famous soon enough
By assigning newSend to the prototype of XMLHttpRequest you are correctly changing the scope to the prototype ... so "this" will refer to the current XMLHttpRequest object.

But for newORSC you are not doing this. So most probably "this" will instead refer to the global window object ... which will obviously fail.

Possible solution (untested): Change the scope for the newORSC object using .call()
Code:
   var that = this;
   this.onreadystatechange = function() {newORSC.call(that);};
devnull69 is offline   Reply With Quote
Old 03-15-2012, 09:23 PM   PM User | #3
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,455
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
you have to assign the ready state change function before you call send, so your approach won't work.

you might be able to modify open() to accomplish the same thing.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Reply

Bookmarks

Tags
ajax, xmlhttprequest

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:27 PM.


Advertisement
Log in to turn off these ads.