onreadystatechange is not called in firefox

4.8k Views Asked by At

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??

1

There are 1 best solutions below

2
On

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