[SOLVED] onreadystatechange event not firing with XMLHttpRequest

I can't get my onreadystatechange event to work

Page 1 of 1

2 Replies - 21882 Views - Last Post: 17 October 2010 - 05:52 PM

#1 forest51690   User is offline

  • D.I.C Regular
  • member icon

Reputation: 58
  • View blog
  • Posts: 340
  • Joined: 20-March 09

[SOLVED] onreadystatechange event not firing with XMLHttpRequest

Posted 11 October 2010 - 09:33 AM

Hi all, I can't figure out how my code isn't working. It seems there's something wrong with my AJAX code. The onreadystatechange event does not fire. Here is my code:

function fetchPage() {
    href = "examples/css1/e.html";
    var client = new XMLHttpRequest();
    client.onreadystatechange = function () {
        alert("onreadystatechange");
    }
    alert(client.readyState);
    client.open("GET", href, false);
    alert(client.readyState);
    client.send();
    alert(client.readyState);
}


So with this code, the "onreadystatechange" alert never pops up. What's the problem? Thanks.

This post has been edited by forest51690: 17 October 2010 - 05:54 PM


Is This A Good Question/Topic? 0
  • +

Replies To: [SOLVED] onreadystatechange event not firing with XMLHttpRequest

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5239
  • View blog
  • Posts: 14,033
  • Joined: 18-April 07

Re: [SOLVED] onreadystatechange event not firing with XMLHttpRequest

Posted 11 October 2010 - 11:49 AM

Remember that when you setup a handler on the variable, that attaches it but doesn't stop the rest of the script from continuing on. This means that since you have defined "client" within the scope of the function, when it reaches the end it goes out of scope and throws away your handler attached to it too. Try defining your XMLHttpRequest OUTSIDE of the function so it has a lasting scope. The function you have defined there can setup the handler and send the request, but when the function ends "client" will continue to exist with its handler.

Enjoy!





"At DIC we be XMLHttpRequest flinging code ninjas.... throwing those objects around like ninja stars!" :snap:
Was This Post Helpful? 1
  • +
  • -

#3 forest51690   User is offline

  • D.I.C Regular
  • member icon

Reputation: 58
  • View blog
  • Posts: 340
  • Joined: 20-March 09

Re: [SOLVED] onreadystatechange event not firing with XMLHttpRequest

Posted 17 October 2010 - 05:52 PM

Thank you Martyr2. I found that this line of code,
client.open("GET", href, false);
,
could be changed to
client.open("GET", href, true);

to make it "asynchronous," so that the next line will not execute until the XMLHttpRequest is finished, so the client variable will still be there.

Thanks for your help.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1