Search code examples
javascriptajaxglobal-variables

Using Ajax variable outside of function


I got below code and I want to use ajax response out side of function but it continuously shows me undefined, I know it is easy but how to handle it?

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>test</title>
<script>
 var sourceData;
 var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      sourceData = this.responseText;

     //
    }
  };
  xhttp.open("GET", "http://localhost:34560/test/js/source.json", true);
  xhttp.send();
  document.getElementById("test").innerHTML=sourceData;
</script>

</head>

<body>
 <div id="test"></div> 

</body>

</html>

Update:

I do not want to use ajax inside function as you can see it is inside script tag.


Solution

  • You are running into the problem of understanding asynchronous javascript. Basically, when you call xhttp.send(), javascript sends the request, but the code is not paused. The next line (where you try to use sourceData) is called, and the server has not yet responded to you send() request, so your onreadystatechange function has not been called yet, and sourceData is indeed undefined. If you want to do anything after the server answers to your asynchronous request, you need to put it inside the onreadystatechange function :

      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("test").innerHTML=this.responseText;
        }
      };