aspose file tools*
The moose likes HTML, CSS and JavaScript and the fly likes Inexplicable JavaScript behaviour Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Inexplicable JavaScript behaviour" Watch "Inexplicable JavaScript behaviour" New topic
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: 61773
    
  67

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by 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: 15376
    
    6
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: 61773
    
  67

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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inexplicable JavaScript behaviour