Andrew Fielden
Andrew Fielden

Reputation: 3899

Why does my AJAX request receive null responseText

I'm sending a request to a Java servlet using a Javascript function, and the servlet writes a response with content type set to "text/plain". I've traced this through with Firebug, and request.responseText is always null, even though the request completes with status 200 (OK). Why is responseText null?

I have previously tried this with a Java client, which did successfully receive the response.

  google.maps.event.addListener(map, 'click', function(event) {
    var request = new XMLHttpRequest();
    request.open("POST", <MY URL>, true);
    request.onreadystatechange = function() {
       if (request.readyState == 4) {
                var resp = request.responseText;
                console.log(resp);
        }
    }

    request.send(null);
  });

UPDATE:

Following suggestions in the answer given, I used Chrome, and viewing the Javascript console I noticed the following error

XMLHttpRequest cannot load http://localhost:8080/... Origin null is not allowed by Access-Control-Allow-Origin.

In my server code I used the following to set the appropriate header in the HTTP response

setHeader("Access-Control-Allow-Origin", "*");

And voila - 42K of data returned as expected in the response!

Upvotes: 1

Views: 715

Answers (1)

acanimal
acanimal

Reputation: 5020

Which browser are you using? Try with chrome and see network and console output.

I have similar headaches due the fact I was doing XDR requests. On FF all seems right and a 200 code is returned but with chrome you have more information and will see a 'Access-Control-Allow-Origin' error.

On your server side try to set the "Access-Control-Allow-Origin: *" to allow request from any source page.

Upvotes: 1

Related Questions