javajqueryajaxjsonstruts2

How to send JSON data via Ajax POST request and receive JSON response from an action in Struts 2?


I am trying to understand how to use JSON in Struts 2, and in the process, I'm trying to get a JSON response from Struts 2 action and display an alert for the response. For this I'm using Ajax POST in JavaScript as follows:

function checkButtonClick(id){  

        var btnSave = 'saveAttendees';  
            var atNameList = $('#attName'+id).val();
            var ptNameList = $('#postName'+id).val();
            var aId = $('#at_id'+id).val();
            
            alert("here");
            var arr = {buttonName:  btnSave,
                    attendeesNameList: atNameList,
                    attendeesPostList: ptNameList,              
                    hidden_At_id: aId
                    };
            $.ajax({                            
                data: arr,
                type: 'POST',
                dataType: 'json',               
                url:"meeting_record_form",
                
                success:function(result){
                    alert(result.myMsg);
              },
                error:function(result){
                    alert("error");
              }
            });
}

My Action class contains a String field that I'm trying to display in alert as JSON response. But I have a problem doing this. What am I missing or doing wrong?

My action class is as follows:

private String myMsg;

    public String getMyMsg() {
        return myMsg;
    }

    public void setMyMsg(String myMsg) {
        this.myMsg = myMsg;
    }

private String updateAttendeesRecord() {
        
        
        meetingRecordService.updateAttendeesRecord(attendeesListMethod(), meeting_record);
        setMyMsg("Update Successful!");
            return SUCCESS;
    }

struts.xml file:

 <package name="default" extends="struts-default, json-default">
    <result-types>
      <result-type name="json" class="org.apache.struts2.json.JSONResult" />
    </result-types>
    <interceptors>
      <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
    </interceptors>
    
    <action name="meeting_record_form" class="com.task.action.MeetingRecordAction" method="updateAttendeesRecord">
     <result name="success" type="json" />
    </action>
</package>

My pom.xml:

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-json-plugin</artifactId>
    <version>2.3.15</version>
</dependency>

Solution

  • I've solved my problem by adding myMsg on the json result. Thanks for all the help