jquery ajax- get response string from a function

1k Views Asked by At

I am unable to get the string response from the java function to the ajax call. I am using structs2 . I have wrote a java function that returns a string. the function works properly. but there are some unknown error in the ajax call.

following is my jquery ajax call

<pre>
function saveMyId(){
    $.ajax({
        url : contextPath+'/action/setMyId',
        data: {
            myCode:$("#myCode").val(),
            myId:$("#myId").val()
        },
        type : 'post',
        async:   false,
        success : function(data) {
            alert(data);
            if(data=="success"){
                $( "#dialog" ).dialog("close");
                $('#myId_Validator').text("");
            }
            else{
                $("#myId").val("");
                $("#myId_Validator").val("ID Already exists. Please Choose different one")
            }
        },
        error: function (request, status, error) {
            alert("Something went wrong. Please try again later");
        }
    }); 

and my java function is

public String setMyId() throws SQLException {
    IdAllocationVO idAllocationVO = new IdAllocationVO();
    MyIdServices myIdServices = new MyIdServices();
    logger.debug("set My Id , myCode :"+this.myCode);
    idAllocationVO.setMyCode(myCode);
    idAllocationVO.setMyId(myId);
    int response= myIdServices.getMyIdCount(myId);
    System.out.println("response:"+response);
    if(response==0){
    myIdServices.setSenderId(idAllocationVO);
        return "success";
    }
    else{
        return "fail";
    }
}

I am using structs 2 and the structs.xml tag is

<action name="setMyId" class="com.id.myIsservice.struts.IdAction" method="setMyId">
</action>

The function setMyId() is working correctly. I have checked everything by printing each line. But my issue is the ajax call gets the result as an error. so it alerts the error message "Something went wrong. Please try again later". Why it is so?

1

There are 1 best solutions below

1
On BEST ANSWER

there are three steps you can try to use for finding the reason: 1、If your ajax call is correct? firebug or other page dubugger can show you~ 2、When the 1st step is correct, check the java function to see if it gets the request from page and responses the right result to page IDE debug tools will help you~ 3、Check what results are got by page through firebug you can see the response details, like 'status' and others..., findout if the string has been got~

PS: I see, your java code throw exceptions directly without using try/catch. It's not a good way for users' use~ I suggest you to add try/catch code, with whith maybe help you find error quicker~