• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inexplicable JavaScript behaviour

 
Chetan Pandey
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chetan Pandey
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is their a Way I can force that to happen.

Something like a flush() in Javascript, I guess?

Thanks.

Chetan
 
Eric Pascarello
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65216
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic