Ajax post call to controller getting 400 (Bad Request) - javascript

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
}

Related

How to pass ajax into a spring controller

Am getting values in Ajax page
function GetInfoDivision()
{
var data = $("#storeName").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "hello",
data : JSON.stringify(data),
dataType : 'json',
//timeout : 100000,
success : function(map) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
But Controller page getting null value ...Ajax data value not passed to the controller
#RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(ModelMap model, HttpServletRequest request) {
String sname = request.getParameter("storeName");
System.out.println("s="+sname);
shopModel s = new shopModel();
s.setStoreName(sname);
//boolean result = employeeService.employeeLogin(employee);
boolean result =false;
if(result == true){
model.addAttribute("message", "Successfully logged in.");
}
else
{
model.addAttribute("message", "Username or password is wrong.");
}
return "redirect:index.jsp";
}
You should use the #RequestBody annotation in the parameter of the controller function.
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html
#Autowired
private HttpServletRequest request;
#RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(#RequestBody ModelMap model) {
If storeName is just a string then you can use #RequestParam
#RequestMapping(value="/hello", method = RequestMethod.POST)
public String employeeLogin(ModelMap model, HttpServletRequest request,
#RequestParam(value = "storeName", required = false) String storeName) {
String sname = storeName;
}
and in Ajax call you can have call like
url : "hello" + "?storeName=" + data
and remove below property in Ajax call
data : JSON.stringify(data),
Your Ajax will look like below:
function GetInfoDivision()
{
var data = $("#storeName").val();
$.ajax({
type : "POST",
contentType : "application/json",
url : "hello" + "?storeName=" + data,
dataType : 'json',
//timeout : 100000,
success : function(map) {
console.log("SUCCESS: ", data);
display(data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
#RequestMapping(value = "hello", method = RequestMethod.POST)
#ResponseBody
public String methodname(#RequestParam("data") String data) {
...
return "";
}

What I missed in my AJAX Code?

When user select any value from drop down, then Ajax has to call server and return some values through JSON object.
Here is my Ajax code
//AJAX Security
$('#ddlSecurityLevel').change(function () {
if ($('#ddlSecurityLevel').val() !== 'None') {
$.ajax({
type: 'POST',
url: 'AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=1&ReportName=TotalSales',
contentType: 'application/json; charset=utf-8',
data: 'json',
//dataType: JSON.stringify(Data),
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
//alert("hello");
alert(result.d); // output UNDEFINED
}
function AjaxFailed(result) {
alert("Error");
alert(result.status + ' ' + result.statusText);
}
}
});
Asp.net C# code
public class GetResult
{
public string removedReportName { get; set; }
public string removedColumnNames { get; set; }
public string removedFilterNames { get; set; }
}
public partial class AjaxSecurity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string securityLevelOrUser = Request["securityLevelOrUser"].ToString();
if (securityLevelOrUser.Equals("SecurityLevel"))
{
string jsonString = js.Serialize(getResultBySecurityLevel(Request["SecurityKey"], Request["ReportName"]));
Response.Write(jsonString);
}
else
{
}
}
private GetResult getResultBySecurityLevel(string securityLevel,string reportName)
{
GetResult getResult = new GetResult();
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ReportHide,RColumnName,RFilterName FROM SecurityLevelDetails WHERE SecurityLevel=#SecurityLevel and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#ReportName", reportName);
cmd.Parameters.AddWithValue("#SecurityLevel", securityLevel);
con.Open();
SqlDataReader rd=cmd.ExecuteReader();
while(rd.Read())
{
getResult.removedReportName = rd["ReportHide"].ToString();
getResult.removedColumnNames = rd["RColumnName"].ToString();
getResult.removedFilterNames = rd["RFilterName"].ToString();
}
}
return getResult;
}
}
When I run my Asp.net code with following parameter, It returns values in browser
URL
http://localhost:55047/AjaxSecurity.aspx?securityLevelOrUser=SecurityLevel&SecurityKey=4&ReportName=TotalSales
Response.Write
{"removedReportName":"1","removedColumnNames":"ItemLookupCode,Department","removedFilterNames":"ExtendedDescription,DepartmentName"}
But the output alert is Undefined
Comment data:'json' and Remove d from alert(result.d);
To access the data in js alert you can write like this,
function AjaxSucceeded(result) {
if(result!=null)
{
alert(result[0].removedReportName +"," result[0].removedColumnNames);
}
}
In your Page_Load method, you need to clear out the output and write your own,
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
Please check this link, this is what you need

Passing model from ajax call to spring controller

I read many articles describing this and I tried to use the same mechanism but still it does not work for me.
So, I want to send the object from javascript to my controller.Here is the snippet I tried but error 400(Bad request).
My bean is as follow : (StudentAnswers.java)
public class StudentAnswers {
private Integer testId;
private Integer studentId;
private String[] questionIds;
private String[] answerIds;
..
//all get and set method to access this
}
My javascript file having ajax call is :
function submitTest()
{
var test_id = 1;
var student_id = 1;
var q = [];
q[0] = "question 1";
q[1] = "question 2";
var a = [];
a[0] = "answer 1";
a[1] = "answer 2";
var studentAnswers = {
"testId": test_id,
"studentId": student_id,
"questionIds": q,
"answerIds" : a
};
$.ajax({
type : "POST",
url : "submitTest",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data : studentAnswers,
success : function(response) {
alert('test submitted');
},
error : function(e) {
alert('Error: ' + e);
}
});
Finally, my controller function is :
#RequestMapping(value={"submitTest"},method = RequestMethod.POST)
public ModelAndView submitTest(#RequestBody StudentAnswers studentAnswers)
{
...
return new ModelAndView("student/testBegin");
}
Try to stringify post data like this:
data : JSON.stringify(studentAnswers)
var studentAnswers = new Object();
studentAnswers.testId = "11";
studentAnswers.studentId = "12345";
studentAnswers.questionIds = "secret";
studentAnswers.answerIds ="111";
$.ajax({
url: urlSelected,
type: "POST",
dataType: "json",
data: JSON.stringify(studentAnswers),
contentType: "application/json",
mimeType: "application/json",
success: function (result) {
if (result.success) {
alert(result.message);
} else {
alert(result.message)
}
},
error:function(error) {
alert(error.message);
}
});
Thank you guys for the help.
I tried using JSON.stringify to send the data from AJAX to Controller and it did not work.
JSON.stringify(studentAnswers)
However, when I took a look at the data that I am sending and compare with the type of data expected, I found out that there was a type mismatch.
So, I changed my javascript Object to be identical to my bean. So, following is my object and bean which works fine.
JavaScript Object :
var studentAnswers = new Object();
studentAnswers.testId = 1;
studentAnswers.studentId = 1;
studentAnswers.questionIds = new Array();
studentAnswers.questionIds[0] = "12345";
studentAnswers.answerIds =new Array();
studentAnswers.answerIds[0] = "12345";
Bean :
public class StudentAnswers {
private Integer testId;
private Integer studentId;
private String[] questionIds;
private String[] answerIds;
..
//all get and set method to access this
}
Final AJAX call looks like this :
$.ajax({
type : "POST",
url : "submitTest",
dataType: "json",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data : JSON.stringify(studentAnswers),
success : function(response) {
alert('test submitted');
},
error : function(e) {
alert(e.message);
}
});
Controller Function:
#RequestMapping(value={"submitTest"},method = RequestMethod.POST)
public ModelAndView submitTest(#RequestBody StudentAnswers studentAnswers)
{
System.out.println(studentAnswers.toString());
return new ModelAndView("student/testBegin");
}

Ajax Jquery Post call getting into 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);
}
}
});
}
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;
}
cheers guys...
Very Simple
submitHandler:function(form){
if(confirm("You are about to send Email Communication, Are you sure..?")){
$.ajax({
type: "POST",
url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
data:$(form).serializeArray(),
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);
}
}
});
}
var strResponse=$.ajax({ type: "POST", url: $("#applicationUrl").val() +"/web/utilities/sendEmailMessage",
data: JSON.stringify({emailSubject : emailSub,emailMsg : emailBody}), async: false,
contentType: "application/json;
charset=utf-8", dataType: "json" });
if (strResponse.readyState == 4 && strResponse.status == 200)
return ((strResponse.responseText.indexOf("d") >= 0) ? eval('(' + strResponse.responseText + ')').d : strResponse.responseText);

ModelAndView("/authenticationError"); not working

after getting request from ajax to controller i am not able to move to next page through ModelAndView("/authenticationError.jsp");
controller code
#RequestMapping(value = "/ProcessReject,method = RequestMethod.POST" )
public ModelAndView Reject(#RequestParam(value = "StatusComments") String StatusComments,
#RequestParam(value = "ruleIndex") String ruleIndex,
#RequestParam(value = "country") String country,
HttpSession session) throws Exception {
ModelAndView mav ;
System.out.println("StatusComments "+ StatusComments);
System.out.println("ruleIndex "+ ruleIndex);
System.out.println("country "+ country);
String quicklookid = (String) session.getAttribute("quicklookid");
//rejectRuleBusinessLogic.reject(ruleIndex, country, quicklookid, StatusComments);
mav = new ModelAndView("/authenticationError.jsp");
return mav;
Ajax code
function showRejectStatusMsg(value1, value2)
{
$.ajax({
type: "POST",
cache: false,
url: "ProcessViewRule.ncr",
data:"ruleIndex=" +value1 +"&country="+value2,
success: function(response) {
},
error : function(e) {
alert('Error in response...' + e);
}
});
jsp code -
<a href="javascript:showRejectStatusMsg(<c:out value='${List.ruleindex}'/>, '<c:out value="${List.country}"/>')" id="rejectLink" class="navlink" >Reject</a>))
You are doing it wrong..You need to write .jsp and can set the view as
mav.setViewName("list");
Basically
new ModelAndView("welcomePage", "WelcomeMessage", message);
is shorthand for
ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);

Categories