Radha Radha - 6 months ago 12
Javascript Question

AJAX Post is not Sending Params

Req: in web application using struts/velocity

JavaScript need to pass parameter to a method in Java class. I have used AJAX post call to servlet. But not able to receive the parameter in action class.

JavaScript function

funtion posttoservlet(){
var id=2
var param="Count="+id;
var xmlhttp= new XMLHttpRequest();
xmlhttp.open("POST","DataServlet.action",true);
xmhttp.setrequestheader('contenttype','plain/text');
xmlhttp.send(param);
}


struts.xml


<action name="DataServlet" method="getfromjs" class=com.test.servletpost>
</action>


servletpost.java


public void getfromjs(){

syso(servletactioncontext.getrequest().getparameter("Count")); // This is printing null instead of printing "2". Please advise.
}


I'm confused why the parameter are not posted properly

Answer

The setRequestHeader is wrong:

xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

The current code, doesn't set the request headers. This invalid syntax might also throw an error. Try the above. And note that JavaScript is CaSe SeNsItIvE.

Comments