1

I was trying to make the simplest AJAX request possible, which for some reason (unexpectedly) works in IE, but not in Chrome?

Here is the code:

var x = new XMLHttpRequest();
x.open("GET","style.php",true);
x.send();
alert(x.responseText); 

The last row merely makes an empty 'alert' window pop up.

The PHP code:

    <?php
     header("Content-Type: text/plain");
     echo "HELLO"; ?>

Someone suggested that I put text/plain header before the code, didn't work. The JS console in Chrome shows status as 200, and 800B as received, so the script receives the response, but doesn't see it?

Thank you very much in advance

user3104270
  • 625
  • 2
  • 10
  • 17
  • Because it is Asynchronous! – epascarello Dec 20 '13 at 17:40
  • 1
    Copy the code for the alert and paste it on the next line, then try again. \*mind blown\* `alert(x.responseText);alert(x.responseText);` – Kevin B Dec 20 '13 at 17:41
  • @KevinB The only reason that works is that the request is fast to complete, so by the time you're done clicking "ok" to the first alert, the request has completed and the responseText is now available. However, you don't really want your code to be reliant on convenient timing. – Niall Jan 01 '17 at 16:41

1 Answers1

2

XMLHttpRequest is an asynchronous function.

You should do this :

var x = new XMLHttpRequest();
x.open("GET","style.php",true);
x.send();
x.onreadystatechange = function(response) {
 alert (response.responseText);
};
Paul Rad
  • 4,820
  • 1
  • 22
  • 23
  • 1
    Thank you, but i got "undefined" response. Cannot figure out why. – user3104270 Dec 20 '13 at 19:50
  • @user3104270 I have the same issue, don't know how to fix :( – Mo. Jun 12 '14 at 11:38
  • Nearly but not quite. The onreadystatechange handler will be called multiple times as the readyState changes - only when `this.readyState == 4` is the request complete. Also, the first argument to the handler is not the response, it is the event - you should refer instead to `this`, which will be the XMLHttpRequest instance itself. Putting it all together, your handler function should be something like `function() { if (this.readyState == 4) { alert(this.responseText); } }` – Niall Jan 01 '17 at 16:36