0

I have a servlet that posts data as an xml page.I made it in Eclipse IDE for Java EE and host it on a Tomcat server. The servlet is hosted on http://localhost:8080/Checkers/CheckersServlet. I can open that url in firefox and it loads the xml fine. How do I call on the servlet from the ajax code?

I think it's supposed to be something like the code below, but that does not work for me. (where displayResult(req) is a custom function that does what I want with the xml received from the servlet). I have confirmed through debugging that the problem is not receiving any xml from the servlet.

Do I need to make one of these web.xml files? Or is that handled by Eclipse when I click "new Servlet"

var req = new XMLHttpRequest();
    req.onreadystatechange = function()
    {   
        if(req.readyState == 4)
        {
            displayResult(req);

        }
    }
    var url = "http://localhost:8080/Checkers/CheckersServlet"; 
    req.open("GET",url,true);
    req.send(null);
Adam Sturge
  • 57
  • 2
  • 3
  • 14

1 Answers1

1

If your servlet is accessible via web browser or curl, the problem is on the client side.

Where are you hosting the JavaScript, i.e. what is the URL of the page that runs this JavaScript code? If it is not localhost:8080, you are unfortunately experiencing . To verify that please add the code snippet described in Can I disable SOP (Same Origin Policy) on any browser for development? - it should work after you accept the change in Firefox.

The easiest correct solution is to place your js file somewhere in Eclipse and deploy it Tomcat as well so that it is available under localhost:8080/Checkers/some-file.js (same domain).

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I am not hosting the javascript, it's just directly defined in my ajax code. I'll look for a tutorial on hosting javascipt code. Here is a more detailed post I made earlier before I figured out exactly what my problem was http://stackoverflow.com/questions/9656156/getelementsbytagname-returning-an-empty-list-when-used-on-responcetext-responc – Adam Sturge Mar 12 '12 at 18:10
  • I do not know how to host the javascript file on my server. I added it to the checkers project, but when I click run on the checkers project name and not just on the servlet it asks if I would like to run on server, or as a java applet or java application. If I choose run on server it doesn't seem to work if I try to reference it, the script never loads and the code breaks. – Adam Sturge Mar 12 '12 at 19:46