So, you want to return something from your servlet back to the javascript you called that servlet from. Here is the way, make an XMLHttpRequest object using these lines of code
var reqObject = new XMLHttpRequst(); or new ActiveXObject("Microsoft.XMLHTTP");
now make a request to the servlet's get or post method using the XMLHttpRequst's open method, you can simply do it like this
reqObject.open("GET/POST", "ServletName", true);
now if you have made a request to the server and state of the object reqObject
is being changed then you will want to see the changes that are being made. Call a function when the state of the object is changed
reqObject.onreadystatechange = processRespose;
if you want to send something as parameter to the servlet use send method otherwise send null.
reqObject.send(null);
now if the servlet is returning something in the method you called from .open
the state of the object will be changed and function processResponse will be called.
function processResponse(){
//check whether the response form the server is intact and correct
if(reqObject.status==200 && reqObject.readyState==200){
//simply means we got the response correctly
//Now you can get the response by
var res = reqObject.responseText;
}
}
you can read about the objects methods and properties here
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
I java servlet you just have to send the expected string with the PrintWriter's object. A rough version of Get method would look somewhat like this
doGet(request, response){
PrintWriter out = response.getWriter();
out.println("Javasrvlet");
}