3

In my Java Web application I am calling ajax request as below.

<script type="text/javascript">
function selectTableHandler() {
    console.log("indise selectTableHandler");
    var xhttp = new XMLHttpRequest();

    var selectedTable = document.getElementById('selectTable').value;
    alert(selectedTable);
    xhttp.open("GET", "populateTableColumList.action?tablename="
            + selectedTable, true);
    xhttp.send();
    console.log(xhttp.responseText);
}
</script>

The Action is calling and returns status code 200 as below.

Remote Address:[::1]:8080
Request        URL:http://localhost:8080/ReportBuilder/populateTableColumList.action?tablename=films
Request Method:GET
Status Code:200 OK

But, it gives empty response of XMLHttpRequest. The line console.log(xhttp.responseText); prints nothing. Also, there is no error in console log.

Any suggestions would be appreciated.

Thanks

Rose18
  • 2,892
  • 8
  • 47
  • 98
  • Firts suggestion [visit this page](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest) and [this one](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) – Anonymous0day Oct 15 '15 at 07:15

3 Answers3

5

You need to add a callback function to get the result of the ajax request.

xhttp.onreadystatechange = function() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    console.log(xhttp.responseText);
  }
}
Gayan Charith
  • 7,301
  • 2
  • 20
  • 32
2

Your ajax request is asynchronous. That means it returns the result some time LATER. You will need to install an event handler for onload or onreadystatechange to get the result.

There are plenty of Ajax tutorials on how to do this. Here are a couple useful references:

https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

If you want to use vanilla js you have to attach event handler onreadystatechange which will handle response, but my advice instead of use vanilla js, use library like jQuery to initiate the ajax request. It will be more easily and it will run without problems on all types of browsers. see here. If you want vanilla js, here is a sample snippet:

xhttp.onreadystatechange = function() {
        if (xhttp.readyState == XMLHttpRequest.DONE ) {
           if(xhttp.status == 200){
              console.log(xhttp.responseText);
           }

        }
    }
Nikolay Rusev
  • 4,060
  • 3
  • 19
  • 29