Search code examples
javascriptjqueryajaxdomjquery-templates

Is there a way to change a global variable on the document in the call back xmlHttpReq.onreadystatechange?


I am pretty new to the AJAX thing, but now I want to set some value to a global variable on the document based on status changed in the call back function xmlHttpReq.onreadystatechange, I used something like

function checkFile(fileUrl) {
    var xmlHttpReq = false;
    var self = this;
        // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(self.xmlHttpReq == null){
    alert("Your browser does not support XMLHTTPReq")
    }

    self.xmlHttpReq.open('HEAD', fileUrl, true);
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            if (self.xmlHttpReq.status == 200) { 
         window.rett = 1;
        //alert(window.rett);
           } else if (self.xmlHttpReq.status == 404) { 
         window.rett = 0;
        //alert(window.rett);
            }
        }
    }
    self.xmlHttpReq.send(); 
}

and I use the checkFile in a jquery template like this:

<script id="resultTemplate" type="text/x-jquery-tmpl"> 
        <li> ${checkFile(link)} <b> {{if window.rett ==  1 }} ${link}   {{/if}}</b> </li> 
    </script>

but when I access the window.rett in a Jquery template, it says undefined...

The reason I want to get the global value is that I want to generate different GUI based on the global value.

Maybe this is not a good practice of using global variable? Any suggestion is appreciated.


Solution

  • Most likely because by the time you tried accessing it, the AJAX request has not completed yet (has not reached state 4), thus your global hasn't been declared (or if it was, it still contains the value of the previous result)

    I suggest you use your template from within the callback. That way, by the time your template checks for the value, the value is already there:

    function yourAjaxFunction(arg1, arg2,...,callback){
    
      //all AJAX setup codes here
    
      if (self.xmlHttpReq.readyState === 4) {
        if (self.xmlHttpReq.status === 200) { 
          //sending the callback a 1
          callback(1);
        } else if (self.xmlHttpReq.status === 404) { 
          //sending the callback a 1
          callback(0);
        }
      }
    
      //AJAX send codes
    
    }
    
    //how you should use it
    yourAjaxFunction(arg1,arg2,...,function(rett){
      //use rett here
      //parse template here
    });