www.webdeveloper.com
Results 1 to 4 of 4

Thread: document.onclick and XMLHttpRequest problem

  1. #1
    Join Date
    Aug 2010
    Posts
    2

    Angry document.onclick and XMLHttpRequest problem

    Here's my problem code:

    document.onclick=handler;
    function handler(e) {
    //do stuff
    var params = "something";
    var request = new XMLHttpRequest();
    request.open("GET", "http://www.foo.com/bar.php?" + params, true);
    request.send(null);
    return true;
    }

    Now is user clicks something else but not a link everything works just fine. But if she clicks a link, the bar.php call does not work (never comes to the server).

    If I change the call to a synchronuous one
    request.open("GET", "http://www.foo.com/bar.php?" + params, false)
    also clicking a link works fine. But I would of course prefer the async way.

    What is problem and why? and how to fix it?

  2. #2
    Join Date
    Jun 2007
    Posts
    667
    Presumably you mean links to other pages?

    Apply a 'return false' onclick handler to all links so that they do not navigate. Then in your document.onclick handler if the source element is a link, set a variable to the link's href. Then the onreadystatechange handler of request can navigate to the href after it completes its usual tasks (if any).

  3. #3
    Join Date
    Aug 2010
    Posts
    2
    Am I right in assuming that the problem is the browser navigates away from the page before the async call to the server is completed?

    Is this a problem in all browsers or just in some?

  4. #4
    Join Date
    Jun 2007
    Posts
    667
    Quote Originally Posted by hiijo View Post
    Am I right in assuming that the problem is the browser navigates away from the page before the async call to the server is completed?

    Is this a problem in all browsers or just in some?
    Almost certainly yes and it can't be classed as a problem because it's inevitable; if you set a new URL you abort the current document, which is why the readstatechange handler should do the navigating.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles