Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Send data from doPost() in servlet to AJAX

843842Nov 3 2008 — edited Nov 4 2008
Hi

I need to send data from my servlet to my html(which contains AJAX), so as per the motivation of the AJAX, this should be done without my webpage reloading / refresh.

my code on the ajax side is something like this:
var xmlHttp = false;

function getXMLHttpRequest(val) {
    try{
    	xmlHttp = new XMLHttpRequest();
    }catch(err1){
        try{
        	xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(err2){
            try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}
            catch(err3){ request = null;}
        }
    }
    if (xmlHttp == false) {
        alert("Error creating request object !!");
    }
    else if(xmlHttp != false){
        return xmlHttp;

        
    }
}
var xmlhttp = new getXMLObject(); 

function ajaxFunction() {
	  if(xmlHttp) {
	   var value1 = document.getElementById("value1");
	   xmlHttp.open("POST","ajax_controlller",true); //getname will be the servlet name
	   xmlHttp.onreadystatechange  = handleServerResponse;
	   xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	   xmlHttp.send("value1=" + value1.value); //Posting txtname to Servlet
	  }
	}

function handleServerResponse() {
	if (xmlHttp.readyState == 4) {
	     if(xmlHttp.status == 200) {
//	       document.myForm.message.innerHTML=xmlHttp.responseText;
            
	       alert(xmlHttp.responseText); //Update the HTML Form element
	     }
	     else {
	        alert("Error during AJAX call. Please try again");
	     }
	   }
	}
and the servlet (doPost()) looks like this :



              if(request.getParameter("value1") != null){
			value = request.getParameter("value1");
		}  
		else  
			value = "";

		response.setContentType("text/html");
		
		response.getWriter().write("helllo");
I however, do not understand what is wrong, do I need to specify the name of the html file just like we do in case of RequestDispatcher() methods. I dont think that is the case here ?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 2 2008
Added on Nov 3 2008
4 comments
1,152 views