Question

I need to return response to ajax from struts(1.3.10) action class. am using PrintWriter class to return the response to client(browser). it's worked for sometimes only but some times, it will show response in jsp page.

this is my jsp and ajax function:

<html:submit property="" styleClass="btn btn-success" onclick="doChangePassword()">Ok</html:submit>

 <script type="text/javascript">
        function doChangePassword(){
            //get the form values
            var oldPassword = $('#oldPassword').val();
            var newPassword = $('#newPassword').val();
            var confirmPassword = $('#confirmPassword').val();
            //                alert(customerName+" "+imeiNo+" "+targetName+" "+simNo+" "+duedate+" "+remark);

            $.ajax({
                type: "POST",
                url: "/GPS-VTS/change_account_password.do",
                data: "oldpassword="+oldPassword+"&newpassword="+newPassword+"&confirmpassword="+confirmPassword,
                dateType: "string",
                success: function(response){
                                                            alert(response);
                    var result = $.trim(response);
                    //                                                alert(result);
                    if(result === "oldPassword")
                    {

                            //  Example.show("Hello world callback");
                            alert("Please provide valid entries for Old Password field.");
                            $('#oldPassword').val("");
                        //alert('Product sold successfully.');


                    }
                    else if(result === "newPasswordEmpty"){
                        alert("Please provide valid entries for New Password field.");
                    }
                    else if(result === "newPassword")
                    {
                            alert("Please provide valid entries for New or Confirm Password fields.");
                            $('#newPassword').val("");
                            $('#confirmPassword').val(""); 
                    }else if(result === "success")
                    {
                            alert("Password Successfully Changed.");
                            $('#oldPassword').val("");
                            $('#newPassword').val("");
                            $('#confirmPassword').val("");    

                    }
                },
                error: function(e){
                    alert('Error :'+e);
                }

            });
        }
    </script>

this is my action class(account_password_action.java):

public class account_password_action extends org.apache.struts.action.Action {

/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
private long account_id;
private String encrypted_password = new String();
private String account_name = new String();
private String account_password = new String();

/**
 * This is the action called from the Struts framework.
 *
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 * @throws java.lang.Exception
 * @return
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {




    /*Get Session Value*/
    String acc_name = request.getSession().getAttribute("login_name").toString();

    /*Create Session Factory Object*/
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();

    Transaction t = session.beginTransaction();

    /*Extract user data from Bean class -> account_bean.java*/
    account_password_bean fromBean = (account_password_bean) form;
    String old_password = fromBean.getOldpassword();

    /*get encrypted password from database*/
    Query enc_password = session.createQuery("from account_dao where name=?");
    enc_password.setString(0, acc_name);
    List list = enc_password.list();
    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
        account_dao account = (account_dao) iterator.next();
        account_id = account.getId();
        account_name = account.getName();
        encrypted_password = account.getPassword();
    }

    /*Decrypt the password using AES algorithm*/
    account_password = AESencrp.decrypt(encrypted_password.toString().trim());

    if (!old_password.equals(account_password)) {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("oldPassword");
        out.write("oldPassword");
        out.flush();
        return null;
    }
     else if(fromBean.getNewpassword().equals("") || fromBean.getNewpassword() == null)
    {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("newPasswordEmpty");
        out.write("newPasswordEmpty");
        out.flush();
        return null;
    } 
    else if (fromBean.getNewpassword().equals(fromBean.getConfirmpassword())) {
        String new_password = fromBean.getNewpassword();
        String new_enc_password = AESencrp.encrypt(new_password.toString().trim());
        Query update_query = session.createQuery("update account_dao set password = :newPassword" + " where id = :Id");
        update_query.setParameter("newPassword", new_enc_password);
        update_query.setParameter("Id", account_id);
        int update_status = update_query.executeUpdate();
        t.commit();
    } 
    else {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("cache-control", "no-cache");
        //out.print("newPassword");
        out.write("newPassword");
        out.flush();
        return null;
    }


    PrintWriter out = response.getWriter();
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("cache-control", "no-cache");
    out.write("success");
    out.flush();
    return null;
    //return mapping.findForward(SUCCESS);

}

}

this is my output in chrome browser:

enter image description here enter image description here

firefox browser:

enter image description here

sometimes it will show correct output in alert box:

enter image description here enter image description here

Hi guys, please help me how to view every time show response in alert box. what can i do? what problem? how can i solve it? any browser version problem?

pls pls pls help me guys.........

Thanks in Advance.

Was it helpful?

Solution

In your ajax call , give additional parameter async : false.

   $.ajax({
                    type: "POST",
                    url: "/GPS-VTS/change_account_password.do",
                    async: false,
                    data: "oldpassword="+oldPassword+"&newpassword="+newPassword+"&confirmpassword="+confirmPassword,
                    dateType: "string",
                    success: function(response){
                     .....

           }

Refer this for learn more about synchronous and asynchronous calls in ajax.
Refer this for learn more about ajax calls.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top