Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty response of XMLHttpRequest

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

like image 768
Rose18 Avatar asked Dec 06 '25 01:12

Rose18


2 Answers

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);
  }
}
like image 77
Gayan Charith Avatar answered Dec 08 '25 14:12

Gayan Charith


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

like image 42
jfriend00 Avatar answered Dec 08 '25 14:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!