I am trying to implement ajax in jsp(avoid form submit) using struts2. I used ajax code to pass request via url to struts2 action. But the response from struts2 is not get populated in jap. Its showing “null” value. My code to call a action in jsp using AJAX is as Follows.
function ajaxEditFunctionCall(){
var xmlHttp;
var url = "ajaxcall.action?stateName="+frm.stateName.value;
try{
xmlHttp=new XMLHttpRequest();
}catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
alert(1);
xmlHttp.onreadystatechange = showMessage;
alert(2);
xmlHttp.open("GET", URL, true);
alert(3);
xmlHttp.send(null);
}
function showMessage() {
alert("Inside Show Message1");
alert(xmlhttp.readyState);
if(xmlhttp.readyState==4)
{
alert("Inside Show Message2&ReadyState4");
alert(xmlhttp.responseText);
}
}
Included following code in Action Class:
public String ajaxcall() throws Exception{
System.out.println("Inside AjaxCall");
String errorXml = "This is a Sample to Check";
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
response.setContentType("text/html");
response.getWriter().write(errorXml);
return null;
}
Code included in Struts.xml:
<action name="ajaxcall" class="com.logic.action.CustomerAction" method="ajaxcall">
<result name="success" >/pages/customer/addCustomer.jsp</result>
</action>
I think the error is in the action class-response statement and in struts.xml. Can any one please help me to fix this issue. Thanks in Advance.
Here, the correction needs to be done to the JavaScript function. When you say
var xmlHttp, it has a scope inside the functionajaxEditFunctionCalland not for theshowMessage. Also,xmlhttpinshowMessage()is not same asxmlHttpobject inajaxEditFunctionCall. So, keep thevar xmlHttpdeclaration global and make the corrections. Here is the working code:The Java code is:
The struts.xml is: