EnexoOnoma
EnexoOnoma

Reputation: 8836

How to print the variable outside of the function in JavaScript?

I would like to alert(httpAccept) outside of the function but this is not possible. All actions must me made inside the httpAcceptResponse(data).

When I consol httpAccess after the getHTTP() I get

Resource interpreted as Script but transferred with MIME type text/html: "http://www.domain.com/httpaccept.php?callback=httpAcceptResponse".

What is a workaround for this?

function requestServerCall(url) {
  var head = document.head;
  var script = document.createElement("script");

  script.setAttribute("src", url);
  head.appendChild(script);
  head.removeChild(script);
}



var httpAccept = '';

function httpAcceptResponse(data) {
  httpAccept = data.token;
}

function getHTTP() {
  requestServerCall("http://www.domain.com/httpaccept.php?callback=httpAcceptResponse");
}

getHTTP();

Upvotes: 0

Views: 116

Answers (1)

tcooc
tcooc

Reputation: 21209

You need to bind a callback. Something like:

var httpAcceptResponse;
function getHTTP(callback) {
  httpAcceptResponse = callback;
  requestServerCall("http://www.domain.com/httpaccept.php?callback=httpAcceptResponse");
}

getHTTP(function(data) {
  console.log(data.token);
  // now you have the variable
});

Edit: If you want to use it globally, set it in the callback:

getHTTP(function(data) {
  window.httpAccept = data.token;
});

Note, however, that the variable is not available globally until the callback is called.

Upvotes: 2

Related Questions