I am trying to send AJAX request to Action in which I am sending one parameter from JSP page. So my Action class is receiving the Ajax request but params which I am sending with AJAX class are null
in Action
class.
This is My Action Class:
public class AjaxAction{
String name;
private String welcomeMessage;
public String execute(){
System.out.println("AJax called "+name);
welcomeMessage="Hello"+name;
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWelcomeMessage() {
return welcomeMessage;
}
public void setWelcomeMessage(String welcomeMessage) {
this.welcomeMessage = welcomeMessage;
}
}
This is my struts.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="json" namespace="/" extends="json-default">
<interceptors>
<interceptor-stack name="defaultStack">
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="ajaxAction" class="com.action.AjaxAction">
<result type="json"/>
</action>
</package>
This is my Jsp file:
<title>Struts Ajax Example</title>
<script type="text/javascript">
function ajaxStruts() {
data = {
name:$("#name").val(),
};
alert(data);
$.ajax({
type: 'GET',
contentType:'application/x-www-form-urlencoded',
url:'ajaxAction',
data: $("#ajaxform").serialize(),
success: function(data){
alert(data);
}
});
}
</script>
</head>
<body>
<fieldset>
<form method="POST" id="ajaxform">
Name::<input type="text" id="name" name="name">
<input type="button" name="submit"
value="submit" onclick="return ajaxStruts();">
</form>
</fieldset>
<fieldset>
<div id="ajaxResult"></div>
</fieldset>
</body>
</html>
The problem is with your interceptors in struts.xml
.
Either remove them or specify them properly. You have override defaultstack
Which is not good practice.
You should make your interceptor-stack's name as custom name different from struts stacks.
For Example, name your stack as mystack.
<interceptors>
<interceptor-stack name="mystack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
This means all the interceptors of defaultstack
+ json interceptor. This will be packed in interceptor stack named as mystack