javajqueryajaxjsonstruts2

How to get a String value from the action class with $.getJSON() method in Struts 2?


I'm trying to get a String value from action class using $.getJSON() method, but I'm getting the result as undefined. Here are the code snippets which I have tried with

Script:

$(function() {
        $("#newPostionFormID").submit(
                function() {
                    var formInput = $(this).serialize();
                    $.getJSON('../employeeShifts/addnewposition.action',
                            formInput, function(jsonResponse) {
                                console.log(jsonResponse.positionAdded);
                            });
                    return false;
                });
    });

strus.xml:

<package name="employeeShifts" namespace="/employeeShifts"
                extends="struts-default,json-default">
     <action name="addnewposition" 
        class="com.vgt.intranet.employeeshifts.action.EmployeeShiftAction"
                    method="addNewPosition">
                    <result type="json">
                        <!-- <param name="excludeNullProperties">true</param>
                        <param name="noCache">true</param>
                        <param name="root">positionAdded</param> -->
                    </result>
        </action>
   </package>

action class:

public class EmployeeShiftAction extends ActionSupport {
private String position;
private String positionAdded;

public String addNewPosition() {
    log.info("inside addNewPosition");
    position = this.getPosition();
    log.info("Position: " + position);
    positionAdded = position;
    log.info("positionAdded: " + positionAdded);
    return Action.SUCCESS;
}

public String getPosition() {
    return position;
}

public void setPosition(String position) {
    this.position = position;
}

public String getPositionAdded() {
    return positionAdded;
}

public void setPositionAdded(String positionAdded) {
    this.positionAdded = positionAdded;
}

Console Log:

undefined

I don't know where I went wrong?


Solution

  • Thanks you for all. Here I'm posting the final working struts configuration as an answer with your responses.

    <result type="json">
        <param name="root">action</param>
        <param name="includeProperties">positionAdded</param>
        <param name="excludeNullProperties">true</param>
        <param name="noCache">true</param>
    </result>