0

This is my main code where I try to make a request to "stat.php".

Main code

<!DOCTYPE html>
<html>
 <head>
   <title>test</title>
   <meta charset="utf-8" />
   <link rel="stylesheet" href="style-index.css" />
  </head>
<body>
  <script>
    function test() {
      var req = new XMLHttpRequest();
      req.open('GET', 'http://www.cubeadvisor.fr/stat.php', true); 
      req.send(null);
      document.getElementById("timer").innerHTML=req.responseText;
    }
  </script>
  <button onclick="test()">Click me</button> 
  <p id="timer"> </p>
</body>
</html>

stat.php

<?php header('Access-Control-Allow-Origin: *');   
echo "test";  ?>

Nothing is returned and I can't find any error. I'm asking your help to solve this problem.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

1 Answers1

2

This is an asynchronous event. You need to use the onreadystatechange event to listen till the response is got from the server and then fire your update function.

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

Working Snippet

<script>
  function test() {
    var req = new XMLHttpRequest();
    req.open('GET', 'http://www.cubeadvisor.fr/stat.php', true);
    req.send(null);
    req.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("timer").innerHTML = this.responseText;
      }
    };
  }
</script>
<button onclick="test()">Click me</button>
<p id="timer"></p>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252