2
function calculateDateDiff(fromDate, toDate) {
    var fromDate = $('#fromDate').val();
    var toDate = $('#toDate').val();

    alert('hi' + fromDate + ' ' + toDate);
    $.ajax({
        type : 'post',
        url : 'calDuration.action',
        dataType : 'json',
        data : $('#createLeaveForm').serialize(),
        success : function(data) {
            alert('success');
            var obj = data;
            $('#leaveDuration').val(obj.effectiveLeavePeriod);
            $('#suffix').val(obj.suffixPrefix);
              var actionErrs= (data.actionErrors); // list of action errors
                var actionMsgs= (data.actionMessages); // list of action messages
                var fielderror= (data.fieldErrors);
                alert(actionErrs);
                alert(actionMsgs);
                alert(fielderror);


            //alert(data.effectiveLeavePeriod);
            $("#ajax_loader").hide('slow');
                showDialog(data);

                  var actionErrs= (data.actionErrors); // list of action errors
                    var actionMsgs= (data.actionMessages); // list of action messages
                    var actionFldErrs= (data.fieldErrors); // list of field errors

                   var alertMessage="";
                    var i=0;
                    for(i=0;i<actionErrs.length; i++){
                    alertMessage=alertMessage+" "+actionMessages[i];
                    }

                    alert(alertMessage);
                    document.getElementById("err").innerHTML=alertMessage;

            /* if (data.indexOf("Successfully") != -1) {
                showDialog(data);
            } else {
                showNormalDialog(data);
            } */

        },
        error :function(data) { 
            showNormalDialog(data);
            alert('Some error occured');
            }
    });
}
   <action name="calDuration" class="in.gov.cg.action.DSChipsLeaveManagementAction" method="calculateDuration">
         <interceptor-ref name="loggingStack"></interceptor-ref>
             <result name="success" type="json"></result>   
             <interceptor-ref name="jsonValidationWorkflowStack"></interceptor-ref>
             <param name="ignoreHierarchy">false</param>
            <param name="includeProperties">actionErrors\[\d+\], fieldErrors\..+$, actionMessages\[\d+\]</param>
            <result name="error" type="json">/pages/common/finishTask.jsp</result>
                </action>
public String calculateDuration() {

    String outcome = "notDone";

    JSONObject obj = new JSONObject();
    JSONArray jsonGroupListArray = new JSONArray();
    try {
        startDate = ApplicationUtil.generateDateFromString(leaveVO
                .getStartDate());
        endDate = ApplicationUtil.generateDateFromString(leaveVO
                .getEndDate());
        halfDay = ApplicationUtil.getBooleanFromDB(leaveVO
                .getHalfDayString());
        System.out.println(halfDay);

    } catch (ParseException e1) {
        e1.printStackTrace();
    }

    if (loginVO == null) {
        loginVO = (LoginUserVO) this.getSession().get("LoggedInUser");
    }

    if (startDate == null || "".equalsIgnoreCase(startDate.toString())) {
        addActionMessage(getText("error.mandatory.StartDate"));
        return "error";
    }
    if (endDate == null || "".equalsIgnoreCase(endDate.toString())) {
        addActionMessage(getText("error.mandatory.EndDate"));
        return "error";
    }
    if (startDate != null && endDate != null) {
        if (startDate.compareTo(endDate) != 0) {
            if (startDate.after(endDate)) {

                addActionMessage(getText("please select proper Date"));
                Date date = null;
                leaveVO.setToDate(date);
                return "error";
            }
        }
    }
        int holidayCount = 0;
        String totalDayCount = "";
        String userLeaveMsg = "";

        try {

            String msg = " Holiday List :";
            totalDayCount = ApplicationUtil.calculateDaydiffernce(
                    new java.sql.Timestamp(startDate.getTime()),
                    new java.sql.Timestamp(endDate.getTime()));
            if (totalDayCount.equals("")) {
                totalDayCount = "0";
            }
            holidayList = LeaveManager.getInstance()
                    .getHolidayList(loginVO);

            endDate = ApplicationUtil.getSQLDateFromUtilDate(endDate);
            startDate = ApplicationUtil.getSQLDateFromUtilDate(startDate);

            for (HolidayVO holiday : holidayList) {

                if (holiday.getCalDate().compareTo(endDate) == 0) {
                    if (holiday.isIsUserLeave()) {
                        userLeaveMsg = userLeaveMsg.concat(ApplicationUtil
                                .generateStringFromUtilDate(holiday
                                        .getCalDate()));
                    }
                }
                if (holiday.getCalDate().compareTo(
                        ApplicationUtil.getNextDate(endDate)) == 0) {

                    suffixPrefix = suffixPrefix
                            .concat("Suffix::")
                            .concat(ApplicationUtil
                                    .generateStringFromUtilDate(holiday
                                            .getCalDate())).concat(" is ")
                            .concat(holiday.getRemarks());
                    leaveVO.setSuffixPrefix(suffixPrefix);

                }

                if (startDate.compareTo(endDate) != 0) {
                    if (holiday.getCalDate().after(startDate)
                            && holiday.getCalDate().before(endDate)) {
                        msg = msg.concat(ApplicationUtil
                                .generateStringFromUtilDate(holiday
                                        .getCalDate()));
                        System.out.println(msg);

                        suffixPrefix = suffixPrefix
                                .concat("Suffix::\n")
                                .concat(ApplicationUtil
                                        .generateStringFromUtilDate(holiday
                                                .getCalDate()))
                                .concat(" is ")
                                .concat(holiday.getRemarks()).concat("\n");
                        System.out.println(suffixPrefix);
                        addActionMessage(getText(msg));
                        holidayCount++;
                        leaveVO.setSuffixPrefix(suffixPrefix);
                    }
                }
                effectiveLeavePeriod = String.valueOf(Integer
                        .valueOf(totalDayCount)
                        - Integer.valueOf(holidayCount) + 1);
                // effectiveLeavePeriod=String.valueOf(Integer.valueOf(totalDayCount)+1);
                // leaveTypeBal =
                // UserManager.getInstance().populateMasterList(loginVO);
                for (LeaveUserVO leavev : leaveBalDetail) {
                    // To check applied duration does not exceeds the
                    // current available balance
                    if (leavev.getLeaveTypeID().equals(
                            leaveVO.getLeavetype())) {
                        if (Double.valueOf(effectiveLeavePeriod) > Double
                                .valueOf(leavev.getLeaveCurrBalance())) {
                            addActionMessage(getText("levae balance is low")
                                    .concat(String
                                            .valueOf(effectiveLeavePeriod)
                                            .concat(String.valueOf(leavev
                                                    .getLeaveCurrBalance()))));
                            System.out.println("levae balance is low"
                                    + String.valueOf(leavev
                                            .getLeaveCurrBalance()));
                            // effectiveLeavePeriod = "0";
                            return "error";
                        }
                    }


                }

            }
            if (leaveVO.getLeavetype() != null
                    && leaveVO.getLeavetype().equals("14")) {
                effectiveLeavePeriod = String.valueOf(Integer
                        .valueOf(totalDayCount) + 1);
            }
        } catch (Exception e) {
            String errorTicketNumber = CommonMBeanHelper
                    .getErrorTicketNumber(e, MODULE.LEAVE);
            log.error("Error ticket number is: " + errorTicketNumber);
            log.error("Exception in init -- > ", e);

        }

        if (halfDay == true) {
            double leavePeriod = Double.valueOf(effectiveLeavePeriod);
            duration = (leavePeriod - 0.5);
            leaveVO.setLeaveDuration(duration);
            effectiveLeavePeriod = String.valueOf(leaveVO
                    .getLeaveDuration());

        } else {

            leaveVO.setLeaveDuration(Double.valueOf(effectiveLeavePeriod));
        }

        obj.put("effectiveLeavePeriod", effectiveLeavePeriod);
        obj.put("suffixPrefix", suffixPrefix);
        //obj.put("MSG", arg1)
        jsonGroupListArray.add(obj);

        System.out.printf("durationValue JSON: %s", jsonGroupListArray);
        JSONObject finalObj = new JSONObject();
        finalObj.put("data", jsonGroupListArray.toString());
        finalObj.put("status", "success"); // final jsonobject for status
        finalObj.put("message", " duration calculate.");


    return "success";
}

how can I return Error message when I select wrong date or have no proper balance using json and struts2 .

I have here finishTask.jsp in which addActionMessage and AddErrorMessage are declared .I am getting the duration only once success is happened .

Roman C
  • 49,761
  • 33
  • 66
  • 176
pink
  • 41
  • 5
  • 1
    1) There's too much code, reduce it to a readable amout, 2) If you use a Struts tag it's obvious it renders the output only when the page is rendered; if you use AJAX, you need to manipulate the returning data on your own – Andrea Ligios Apr 19 '17 at 12:46
  • What a mess. Your error result is nonsense. Your `finalObj` isn't included in json. – Aleksandr M Apr 19 '17 at 15:16
  • Aleksandr M please tell me how can I correct it? – pink Apr 20 '17 at 05:29
  • @pink You can't correct it, first you need to reconfigure the interceptor stack, then configure exception interceptor to return result error to the ajax responce, the error result should be handled by the error callback function. You need to choose which library do you need to use for json handler. Don't do it yourself, let the framework do the stuff. – Roman C Apr 20 '17 at 09:26
  • @RomanC I configured interceptor stack and add library struts2-json-plugin .still i m not able to handle error using struts2 and json .Is there any other library for error handle in json and struts2? – pink Apr 20 '17 at 11:57
  • You can find them in [this](http://stackoverflow.com/a/43207860/573032) answer – Roman C Apr 20 '17 at 12:13
  • I have added jar file in my project still I facing same issue .json doesnt return error – pink Apr 20 '17 at 13:10
  • What do you mean *.json doesnt return error*? – Roman C Apr 20 '17 at 15:27
  • I mean when i input wrong date,or user has no leave balance so it goes to return "error" ; this error action and message from addAction("no balance") never execute and never give an alert message in my jsp page.Please tell me how can i perform this operation – pink Apr 21 '17 at 07:26

0 Answers0