| Author |
Inexplicable JavaScript behaviour
|
Chetan Pandey
Ranch Hand
Joined: Aug 01, 2005
Posts: 31
|
|
Hi All: I am using Javascript in my Struts-1/Spring-Hib Project along with prototype.js for helping me in making Ajax Calls. Browser: 7.0.5 I have Code the skeleton of which is: So the Logic that is happening above is declare a Global Varibale globalVar1 Make a ajax Call and set this globalVar1 to the request.responseText Then in the calling function alert(globalVar1); set id = globalVar1; Check value of id by doing alert('id = ' + id); the funny thing that is happening is that if I remove alert(globalVar1), id shows as null, but if I let it be their then id shows the correct numeric Value. Correctness of value passed by request.repsonseText has been verified in both Cases. So can anyone tell me why that alert(..) is causing variant behaviour
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56528
|
|
All of the code in the fetchId function after the call makePrototypeAjaxCall executes immediately, before the Ajax request has a chance to finish. The alert seems to fix things because the delay caused by the alert allows the request to complete. You can't do anything that relies upon the completion of the request before the request completes. That's what the onComplete callback is for.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Chetan Pandey
Ranch Hand
Joined: Aug 01, 2005
Posts: 31
|
|
Is their a Way I can force that to happen. Something like a flush() in Javascript, I guess? Thanks. Chetan
|
 |
Eric Pascarello
author
Rancher
Joined: Nov 08, 2001
Posts: 15362
|
|
Bear pointed out that you are doing an asynchronous request. It allows other things to happen. So the code is working exactly the way it is supposed to. If you do not want that to happen, you need to learn about synchronous requests, but using it is not highly recommended. Eric
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56528
|
|
The fix is to move anything that needs to wait until the request is complete into the onComplete handler or to code that is called from that handler. Your problem was created when you put code that needs to wait until the request finishes in the function that kicked off the request. Any such code needs to be moved. [ November 02, 2007: Message edited by: Bear Bibeault ]
|
 |
 |
|
|
subject: Inexplicable JavaScript behaviour
|
|
|