Im Using Ajax to get success response from Struts 2 but it ended up giving the response to error function and parse error for parsing JSON in Ajax.
Below is my code.
Action class - PropertyTesting.java
import java.io.IOException;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class PropertyTesting extends ActionSupport
{
public String execute()
{
JSONObject obj = new JSONObject();
obj.put("Name", "PersonName");
obj.put("ID", "PersonID");
try {
ServletActionContext.getResponse().getWriter().write(obj.toJSONString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
}
JSP Page - PropertyTesting.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Property Testing</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
function invokeAjax()
{
$.ajax(
{
type:"POST",
url:"PropertyTesting",
dataType:"json",
success: function(responseText)
{
console.log(responseText);
},
error: function(errorResponse)
{
console.log(errorResponse);
}
});
}
</script>
</head>
<body>
<button type="button" onclick="invokeAjax()" >Submit</button>
</body>
</html>
Struts.xml
<struts>
<constant name="struts.devMode" value="true"/>
<package name="WebTesting" extends="json-default">
<action name="PropertyTesting" class="org.testing.PropertyTesting" >
<result type="json"></result>
</action>
</package>
</struts>
And also if i'm doing the same thing using Servlets its giving me the exact results on using struts only giving this kind of problems.