RameshVel
RameshVel

Reputation: 65867

onreadystatechange event problem in AJAX call?

The problem seems very strange. I have a AJAX helper function within a same aspx file and onreadystatechange event is handled like this

      xmlhttp.onreadystatechange = function(){
             if (xmlhttp.readyState == 4)
                   //do some opp
      }

this works fine. i can read the xmlhttp value inside the callback.

And i moved the AJAX helper methods to addition js file. And i have created a method something like this

   function AjaxHelper() {
       this.GetValue = function(sData, sMethod, assembly, json, aSyncfunction) {
          var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

         if (typeof(aSyncfunction) != "undefined" && aSyncfunction != null) {
            xmlhttp.onreadystatechange = aSyncfunction
         }

         //Ajax open and send code here

       }
   }

Now i create a callback function in my aspx file and called the AjaxHelper.GetValue() function

     var callback=function(){
        if (xmlhttp.readyState == 4)
                   //do some opp

     }

     AjaxHelper.GetValue("test","getTest()","UIhelper","",callback) 

And the callback function is suceesfully called everytime after the state changes, but i cant reference the xmlhttp variable. its always undefined.

I though its going to execute in the AJaxhelper context, but its not.

Can anybody calrify me how to solve this

Upvotes: 0

Views: 793

Answers (1)

bobince
bobince

Reputation: 536349

I though its going to execute in the AJaxhelper context, but its not.

No. JavaScript is lexically scoped. Once you finish the function GetValue, the local variable xmlhttp is no longer accessible. If there are no closures inside the function's scope retaining a reference to xmlhttp, as in this case there aren't, the variable xmlhttp is gone forever.

You might want to have a closure retain xmlhttp in GetValue and pass it to the callback function:

if (aSyncfunction) {
    xmlhttp.onreadystatechange= function() {
        aSyncfunction(xmlhttp);
    };
}

Or you could assign the object to a member variable like this.xmlhttp where it will be visible to other functions inside and outside the object.

PS. also caution, JavaScript is case-sensitive:

var xml​H​ttp

Upvotes: 2

Related Questions