1

I'm trying to get a Java Servlet to send some HTML as a response to a request from a JavaScript function. However, while the servlet function is getting called and seems to be sending a response, the Javascript functions is getting nothing but an empty String.

Here is the Servlet method:

String type = request.getParameter("type");
if(type.equals("locos")) {
            response.setContentType("text/html");

            //this prints out
            System.out.println("Responding with vehicle list");

            //deal with response
             PrintWriter out = response.getWriter();
             out.write("<p>test response</p>"); //finish
        }

Here is the JavaScript function:

this.updateVehicleList = function () {
        var type = "locos";

        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),true);
        xhr.send(null);

        //deal with response
        var res = xhr.responseText;

        //for testing
        if (res == "") {
            window.alert("I'm getting nothing");
        }

        view.showVehicleList(res);
    };

The "I'm getting nothing" message outputs every time. How do I get the JavaScript to actually receive the response from the Servlet?

Cailean
  • 37
  • 2
  • 9
  • Related: [How to use Servlets and Ajax?](http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax) – BalusC Apr 03 '16 at 13:56

1 Answers1

1

You are making an asynchronous request and so the response is not immediately available. You are trying to get the responseText before the response has even been received.

Use the onreadystatechange event:

...
...
xhr.send(null);

xhr.onreadystatechange = function () {
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){
        //deal with response
        var res = xhr.responseText;

         //for testing
         if (res == "") {
            window.alert("I'm getting nothing");
         }

        view.showVehicleList(res);
    }
};

If you are intending to make a synchronous request, then set the third argument to false and your original code will work.

xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),false);
//                                                         ^^^^^
MrCode
  • 63,975
  • 10
  • 90
  • 112