简体   繁体   中英

Ajax post call to controller getting 400 (Bad Request)

I am trying to implement an ajax call using jquery.when i am submitting the call, it is throwing 400 Bad Request..Not sure where i am doing wrong in my ajax call..Need help in fixing this..

 submitHandler:function(form){
            var emailSub = $("#emailSubTxtArea").val();
            var emailBody = $("#emailBodyTxtArea").val();
            if(confirm("You are about to send Email Communication, Are you sure..?")){
            $.ajax({
                type: "POST",
                url:  $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
                dataType: "json",
                //cache:false,
                contentType: "application/json; charset=utf-8",
                data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}), 
                success:function(data)
                {
                    console.log("Sending Email Notification was success.");
                },
                error: function(x, t, m) {
                    console.trace();
                    if (!(console == 'undefined')) {
                    console.log("ERROR: " + x + t
                            + m);
                    }
                    }
           });
        }
return false;
        }

my Controller code:

@RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
    public ModelAndView sendEmailCommunication(@RequestParam("emailSubject") String emailSubject,@RequestParam("emailMsg") String emailBody,HttpServletRequest request){
        ModelAndView view = null;
        StringBuffer sMsg = new StringBuffer();
        StringBuffer eMsg = new StringBuffer();
        boolean isAdmin = false;
        try{
        String loggedInUser = request.getHeader("sm_user").trim();
         isAdmin = getUserAdminRights(request);
        if(isAdmin){
            boolean status = emailService.sendEmailCommuncation(emailSubject,emailBody);
            if(status){
                sMsg.append(" Sending SiteMinder Notification Email was Success.");
            }
            else{
                eMsg.append(" Oops! Something went wrong while sending Email Notification. Pls check logs");
            }
        }
        else{
             view = new ModelAndView("redirect:/web/utilities/not_authorized");
             return view;
        }
        }
        catch(Exception ex){
            ex.printStackTrace();
            eMsg.append("Oops! Something went wrong while sending Email Notification. Pls check logs");
        }
        view = new ModelAndView("EmailCommunication");
        view.addObject("isAdmin", isAdmin);
        view.addObject("sMsg", sMsg.toString());
        view.addObject("eMsg", eMsg.toString());
        return view;
    }

I am really beating my head for last 4 hrs..help needed . thanks..

You need quotes around your data keys . Change emailSubject: emailSub,emailMsg : emailBody to "emailSubject" : emailSub, "emailMsg" : emailBody .

You're also missing a closing } at the very end of your submitHandler , could just be a paste error?

dont stringify the data

Change

data:JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}),

 to

data:{emailSubject : emailSub,emailMsg : emailBody},

i made the changes to my ajax call and the controller which now user @RequestBody and now it is working fine...

my ajax code:

 submitHandler:function(form){
            var jsonObj = getData();        
            if(confirm("You are about to send Email Communication, Are you sure..?")){
            $.ajax({
                type: "POST",
                url:  $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
                dataType: 'json',
                cache:false,
                headers: { 
                    'Content-Type': 'application/json' 
                    },
                data:JSON.stringify(jsonObj),
                //data: ({emailInfo : JSON.stringify({emailSubject:emailSub,emailMsg:emailBody})}),
                success:function(response)
                {
                    response.html();
                },
                error: function(x, t, m) {
                    console.trace();
                    if (!(console == 'undefined')) {
                    console.log("ERROR: " + x + t
                            + m);
                    }
                    }
           });
        }
            return false;
        }
function getData(){
    var object ={
            emailSubject : $("#emailSubTxtArea").val(),
            emailMsg : $("#emailBodyTxtArea").val()

    };
    return object;


}

controller:

@RequestMapping(value="/sendEmailMessage",method=RequestMethod.POST)
    public ModelAndView sendEmailCommunication(@RequestBody EmailReqInfo emailInfo){
        ModelAndView view = null;
        StringBuffer sMsg = new StringBuffer();
        StringBuffer eMsg = new StringBuffer();
        boolean isAdmin = false;
        try{
        String loggedInUser = request.getHeader("sm_user").trim();
         isAdmin = getUserAdminRights(request);
            String emailSubject = emailInfo.getEmailSubject();
            String emailMsg  = emailInfo.getEmailMsg();
--
----

domain:-

    public class EmailReqInfo implements Serializable
    {

        private static final long serialVersionUID = 1L;
        private String emailSubject;
        private String emailMsg;

//getters and setters
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM