0

I am trying to make an AJAX call that will return me the echo of a php file, but it is not working... All the documents are in the same folder.

.html file (javascript part):

<script>

function GetData()
{
var xmlhttp;

  xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    return xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

var Order2 = GetData();
document.getElementById('Order2').innerHTML = Order2;
</script>

.php file:

<?php
echo "HELLO!";
?>

Does anyone know why this is not working? My browser is Google Chrome.

Thanks in advance :)

Topast
  • 23
  • 3

1 Answers1

3

You should change your approach when you work with asynchronous operations (AJAX, timeouts). Something like this:

function GetData(callback) {

    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", "test.php", true);
    xmlhttp.send();
}

GetData(function(data) {
    document.getElementById('Order2').innerHTML = data;
});

You can't return because by the time you return response is not yet available. That's why you use callback functions to be called once response has come.

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • +1 Yes, the "asynchronous" in AJAX means you don't get a return value right away, that's why you need a callback that will get called whenever the result is received. – Matt Browne Apr 20 '14 at 13:21
  • Seems like that was the problem. Thanks :) – Topast Apr 20 '14 at 16:23