2

Here are my codes.

my function to send ajax request and return a value:

function myAjaxCall(){
   var myValue=0
   var async= false //I have to use synchronized request(otherwise my return value is 0)
   xmlhttp.open("GET",URL,async);

   xmlhttp.onreadystatechange=function(){
       ...
       myValue = SOMEVALUE;
   };

   xmlhttp.send();         

   return myValue
}

My other function will use the myAjaxCall function returned value

function otherFunc(){
   var x= myAjaxCall();
}

Things are working perfectly in this way except on Firefox browser, I know the reason is because in Firefox, if I use synchronized request, the onreadystatechange will not be called.

In my case, however, I have to use synchronized ajax request, otherwise myAjaxCall() function returned value is always the initail value "var myValue=0".

How to get rid of this firefox problem??

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • 6
    Don't use synchronized Ajax requests just to be able to return something straight away - they stop everything else on the page and can freeze the browser. It's *way* better to change the architecture of your program instead – Pekka Feb 10 '11 at 14:38
  • What kind of architecture I can have in my case then..... – Mellon Feb 10 '11 at 14:57
  • Use `otherFunc` as your callback handler and access `xmlhttp.responseText` therein. – Marcel Korpel Feb 10 '11 at 15:00
  • Firefox versions before Firefox 4 don't fire onreadystatechange for synchronous XMLHttpRequest, as you noticed. But since this is a synchronous request, why do you need the onreadystatechange handler in the first place? – Boris Zbarsky Apr 23 '11 at 04:11

1 Answers1

3

Use a function pointer instead of an inline function to avoid this issue:

function myAjaxCall(){
   var myValue=0;
   var async= true;

   xmlhttp.open("GET",URL,async);
   xmlhttp.send();
   xmlhttp.onreadystatechange=foo;         
  }

function foo(bar)
  {
  var myValue = SOMEVALUE;
  return myValue;
  }

Functions control scope in JavaScript, so:

  • The anonymous function creates a new scope, while the referenced function is in the global scope
  • Moving the function out of scope avoids the namespace conflict
  • myValue inherits a value in the new scope, while it does not in the global scope

Also, send should be done before onReadyStateChange

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265