0

I am trying to get the value of GetURL in the New_Token function back out of the function so that I can use it. I think my problem is the request.onreadystatechange line (although I can't be sure). GetURL is undefined outside of the function.

var GetURL;
var request = new XMLHttpRequest();
var path="https://ops.epo.org/3.1/auth/accesstoken";

request.onreadystatechange= function() {New_Token(GetURL);};

var encodedData = window.btoa("key:secret"); //encode consumer key and secret key
request.open("POST", path, true);
request.setRequestHeader("Authorization", encodedData);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('grant_type=client_credentials'); //send request to server, must include grant_type in payload or it won't work
alert(GetURL);

function New_Token(GetURL) {
    if (request.readyState == "4") //Request finished and response is ready
    {
        if (request.status == "200") {
            console.log(request.responseText);
            var TheResponse = JSON.parse(request.responseText);
            console.log(TheResponse);
            var TokenValue = TheResponse.access_token;
            console.log(TokenValue);
            GetURL = ("?access_token=" + TokenValue);
            console.log(GetURL); //this is the added string that needs to be concact. on to ALL OPS calls

            return(GetURL);
        }
        else {
             alert("Problem retrieving data");
            console.log(request.responseText);
        }
    }
}

1 Answers1

0

Try this

function New_Token(GetURL) {
    if (request.readyState == 4 || request.readyState == "complete") 
    {
        if (request.status == 200||request.status == 0) {
            console.log(request.responseText);
            var TheResponse = JSON.parse(request.responseText);
            console.log(TheResponse);
            var TokenValue = TheResponse.access_token;
            console.log(TokenValue);
            GetURL = ("?access_token=" + TokenValue);
            console.log(GetURL); //this is the added string that needs to be concact. on to ALL OPS calls
            return(GetURL);
        }
        else {
             alert("Problem retrieving data");
            console.log(request.responseText);
        }
    }
}
  • The old code gets the correct value for "GetURL" in the New_Token function. What I'm trying to figure out is how to make GetURL global (or at least be returned so I can access it outside of the function). My apologies if I am missing something, but I don't believe your code is responding to that problem. – Learning2Prgrm Apr 13 '16 at 17:36
  • My respectful apologies for misunderstanding your question. –  Apr 13 '16 at 17:39