Win a copy of Modern frontends with htmx this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Ajax and "this"

 
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IE7 supports XMLHttpRequest.
So I store reference in javascript as
this.httpRequest = new XMLHttpRequest();

now after readystatechange if I use this.httpRequest it becomes undefined.
Any variable prefixed with this becomes undefined.

If we use ActiveXObject (supported by ie6, ie5) in ie7 than this prefix is not a problem.

How can I prove this to my seniors.
[ April 26, 2007: Message edited by: Bear Bibeault ]
 
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can you show us the readystatechange code.
 
Santana Iyer
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Eric,

I am not able to put code it gives me errors always.....

Sorry for that but it goes like this,


// in openConnection I get XmlHttpRequest or ActiveXObject and store it in this.http_request // reference
if(openConnection()) {

this.http_request.onreadystatechange = function() {
if (this.http_request.readyState == 4) {
if (this.http_request.status == 200) { ............


Now it gives me error as this.http_request.readyState is undefined.

I tried putting alerts and conclusion I came to was as soon as state changes in connect method all variable prefixed by this becomes undefined.

If you remove this prefix than it works fine.

I don't know why but this is what I observed.
[ April 25, 2007: Message edited by: Santana Iyer ]
 
Sheriff
Posts: 67745
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is it that you are expecting this to point to? That object is known as the function context and it is set according to specific rules based upon how you are calling your functions/methods.

Without seeing the code, it's hard to help.
[ April 25, 2007: Message edited by: Bear Bibeault ]
 
Eric Pascarello
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As Bear says this no longer points to your object like you expect it too.

try doing:


Eric
 
Ranch Hand
Posts: 409
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interesting question. I'd like to know more. Do either of the following make sense?





[bear edit: code reformatted to play more nicely in the browser]
[ April 26, 2007: Message edited by: Bear Bibeault ]
 
Bear Bibeault
Sheriff
Posts: 67745
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The difference is that the function code is looking for the XMLHttpRequest instance in different places.

In the first example, the code assumes that the instance is a property of the function context. Exactly what object is serving as the function context is dependent upon how the code was declared and invoked. So trying to figure it out with small code snippets is impossible.

The second example assumes that the XMLHttpRequest instance is a property of the window.

Since both examples start off assuming that the instance is a property of 'req' (whatever that is), it's unlikely that either assumption is valid.
[ April 26, 2007: Message edited by: Bear Bibeault ]
 
Roger F. Gay
Ranch Hand
Posts: 409
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sorry for not defining that in my code above. It's so common (request) in many first Ajax examples out on the web, and I have stared at it so much in working with it, that I started taking it for granted.

I have yet to try many XMLHttpRequest:s in the same page. So far, my own Ajax page has only one req fired by a click that calls a function. ....

So, from there, it seems the issue for me related to this discussion; is in handling many requests -- such that defining req as a global variable suddenly becomes totally inadequate. req is actually going to be whatever it was defined to be from the last XMLHttpRequest, which is not necessarily the one that the callback function is supposed to be processing.

(Right so far?)

So if req = new XMLHttpRequest(), and req.onreadystatechange = callback, does "this" in the function context refer to the specific instance of req that invokes the callback function?


[ April 26, 2007: Message edited by: Roger F. Gay ]
 
Bear Bibeault
Sheriff
Posts: 67745
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<rententive-personal-rant>
Why do so many developers insist upon freeze-drying their variable names? It drives me up the wall. We're not writing FORTRAN anymore!
</rententive-personal-rant>

Whew! Just had to let that out...


defining req as a global variable suddenly becomes totally inadequate.


As with any other programming language, global variable severly limit the usefullness of the code and should be avoided when possible.

So if req = new XMLHttpRequest(), and req.onreadystatechange = callback, does "this" in the function context refer to the specific instance of req that invokes the callback function?


No, because all this is happening at the global level, the value of the function context is non-determinsitic. The function context (this) is set to something meaningful when the called function is the method of a Javascript object, or when it is explicit set by the caller of the function. This is especially "interesting" in the case of callbacks.

These concepts are a core part of object-oriented Javascript. You may have missed a book promo a few weeks back for the soon-to-be-published book Ajax in Practice where I devoted chapter 3 to just these topics. Appendix B of Ajax in Action (which I believe is freely available) also touches on these topics (though with less focus on OO).

This is also one of the reasons that I think, at this stage of the game, hand-coding Ajax requests at the low-level without the support of one of the freely available libraries such as Prototype or jQuery is simply madness. These libraries handle all these nuances for you so you can concentrate on just writing the code without worrying too much about the plumbing.
[ April 26, 2007: Message edited by: Bear Bibeault ]
 
Roger F. Gay
Ranch Hand
Posts: 409
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My copy of "Ajax in Practice" hasn't arrived yet. I am extremely pleased to learn that this is covered. (Tounge in cheek - "this" is covered.) {Any idea when it will arrive? I was a winner in the promo.)

I sometimes create global variables during prototyping - which I do a lot when I'm trying to learn something. Walk before I run -- it's a convinience -- sometimes.

I think though, I'm not quite getting what you're saying, and it might be nice at this point (as a learning / discussion point) that req is a global variable. (Although I would be more than pleased to change that, once I've pumped as much value as I can out of it.)

Let me explain my thinking, and you can tell me where I'm wrong. I don't think I'm just repeating what's above; I'm thinking that maybe I still haven't clarified enough.


So there it seems as though I've extablished that callback() is the callback function for this instance of req. I'm expecting a handle (or something) to be stored somewhere, so that there is no confusion about which instance of req is being referred to. I'm imagining that at that point, the variable name "req" and the fact that it's a global variable is no longer relevant. I'm imagining that there's a req_handle_001 kind of thing around that points to just the particular instance involved in the return of the Ajax message. (So if I'm terribly wrong about this ....)

So in other words, my imagination has been telling me that when the callback function is called, it will actually be (using my notation above)


so that any "this" in the context of the callback function knows that it is related to req_handle_001.

Bad Bad or .... ??
 
Bear Bibeault
Sheriff
Posts: 67745
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Roger F. Gay:
My copy of "Ajax in Practice" hasn't arrived yet. I am extremely pleased to learn that this is covered. (Tounge in cheek - "this" is covered.) {Any idea when it will arrive? I was a winner in the promo.)



Ah, so you didn't miss the promo! Congrats! The book has been at the bindery for some time now. I'd expect physical copies to start coming out of the end of the building anytime now...



So there it seems as though I've extablished that callback() is the callback function for this instance of req.



Properly stated, you've asigned a reference to the function named callback to the onreadystatechange property of the req instance.

I'm expecting a handle (or something) to be stored somewhere, so that there is no confusion about which instance of req is being referred to.



By who? And where?

I'm imagining that at that point, the variable name "req" and the fact that it's a global variable is no longer relevant. I'm imagining that there's a req_handle_001 kind of thing around that points to just the particular instance involved in the return of the Ajax message. (So if I'm terribly wrong about this ....)



You're imagining things.

There's no magic happening. The instance of XMLHttpRequest simply has the reference that you gave it.

So in other words, my imagination has been telling me that when the callback function is called, it will actually be (using my notation above)


so that any "this" in the context of the callback function knows that it is related to req_handle_001.



Nope. It's not related to anything. A little bit of testing will show you this. In Firefox, for example "this" will be a reference to the callback function itself. In Safari, it's the window. In IE6, it's an object whose nature I don't have the patience to track down. Point is, in this case, the function context is non-deterministic.

There's trickery (called context binding) that can be used -- and indeed is used by libraries such as Prototypye and jQuery -- to force the function context to be something deterministic by using a function wrapper and closures. But that's way beyond the scope of what I can get into in a forum, and not anything that anyone should have to do "by hand" when writing script.

Bottom line: use Prototype or jQuery for all your Ajax needs. There's no reason to have to write pages and pages of plumbing code when such libraries handle all of that on your behalf.

(P.S. All of this is further complicated by the fact that, as with Image, XMLHttpRequest doesn't always act like a typical javascript Object, and those manifestations differ across browsers).
 
Roger F. Gay
Ranch Hand
Posts: 409
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
context binding, function wrapper and closures -- things I need to look into. I understand your comments about using existing libraries. I get kicked around a lot whenever I care about something enough to want to become a guru. Why reinvent the wheel, etc. But of course I haven't written my own browser even though cross-browser applications are the dickens (which would only help of course if ...), I run Apache Tomcat (although I have one project where I need to build my own small simple server), and have never given any consideration whatsoever to building my own socket application for ftp or anything like that. In other words, I do use other people's stuff and have definitely taken advantage of open source freeware.

I have xmljs on my machine, and will get around to it when I have time. I'm even signed up on the email list. Brings up a side issue about JSON. A quick look (don't let me confuse you into thinking I'm a JSON expert yet); something like replacing xml with structures like I used to use in C?

What about all the time and technology spent on XML? I know programming structures can be easier in programming (don't have to go in and out of XML); jdom? But, is the argument that ... now that XML is standard and supported by lots of libraries, we should throw it out and do something else?
 
Bear Bibeault
Sheriff
Posts: 67745
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I get kicked around a lot whenever I care about something enough to want to become a guru. Why reinvent the wheel, etc.



On the other hand, it never hurts to know how the wheels that you are using work.

now that XML is standard and supported by lots of libraries, we should throw it out and do something else?



Absolutely not. Just becasue there are multiple technologies doesn't make one of them "the one true master of them all".

XML has its place. JSON has its. I use whichever one is best suited for the job.
 
Climb the rope! CLIMB THE ROPE! You too tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic