-2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sina Nouri
  • 111
  • 3
  • 13

2 Answers2

1

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;
    }
  };
Katz
  • 165
  • 6
0

You can create a synchronous call rather than async one.

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

Note however that this blocks the script and makes your web page unresponsive until the server reply has arrived. You should learn about asynchronous callbacks instead.

Felix
  • 129
  • 9