Search code examples
javascriptjaggery-js

javascript inner function variable access from outside


Here is my code. I need to access inner function variable in outer function

var json = {}, state, response;
readRequestValues();
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
 if(xhr.readyState == 4){
    json.state = xhr.readyState;
    json.response = xhr.responseText;
    log.info(">>>>>>>>>>>>>>>"+json.state+">>>>>"+json.response);
    var retValue=JSON.stringify(json);
    log.info(">>> THIS IS RESULT >>>"+retValue);

 }
}
xhr.open("GET", strBackend, true);//async=true
xhr.send();

log.info(">>> HERE I NEED TO ACCESS retValue >>>"+retValue);

Thanks


Solution

  • You can't. It not received yet here.
    You should call any code, when we get it:

    var json = {}, state, response;
    readRequestValues();
    var xhr = new XMLHttpRequest();
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange=function(){
     if(xhr.readyState == 4){
        json.state = xhr.readyState;
        json.response = xhr.responseText;
        log.info(">>>>>>>>>>>>>>>"+json.state+">>>>>"+json.response);
        var retValue=JSON.stringify(json);
        log.info(">>> THIS IS RESULT >>>"+retValue);
    
        logValue(retValue); // here we call logger
    
     }
    }
    xhr.open("GET", strBackend, true);//async=true
    xhr.send();
    
    
    function logValue(val) {
      log.info(">>> HERE I NEED TO ACCESS retValue >>>"+val);
    }