How to pass ajax into a spring controller - javascript

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 "";
}

Related

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 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
}

Ajax call to spring controller callback error function

Can you tell me what it's going wrong with the following ajax call to controller ?
The controller that is called via ajax :
#RequestMapping(value = "/userManagement/loadData.html", method = RequestMethod.POST,produces="text/plain")
public #ResponseBody String loadData(#RequestBody String jsonData) {
try {
Map<String, Object> data = JsonUtils.jsonAsMap(jsonData);
pageSize = Integer.valueOf(data.get("pageSize").toString());
pageNumber = Integer.valueOf(data.get("pageNumber").toString());
} catch (Exception e) {
return "failure";
}
return "success";
}
The ajax function :
function reloadUsers(){
$.ajax({
type : "POST",
cache : false,
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
url : "userManagement/loadData.html",
data : JSON.stringify({
pageSize : 10,
pageNumber : 0
}),
success : function(response) {
if(response.responseText=='true'){
console.log('success');
}else{
console.log('server error');
}
},
error : function(jqxhr){
console.log('error');
console.log(jqxhr.responseText);
}
});
}
Now when i execute the ajax call to the controller it always goes on the error function and the jqxhr.responseText is always the value returned by the controller(in this case 'success' or 'failure'.
My question is why is this happening ?
If i change the controller returned values to "true" or "false" the ajax successfully callback the 'success' function.
I also tried with produces="application/json"and got the same result.
Change the datatype to:
dataType: 'text',
As you are going to get a string in response because of this:
#RequestMapping(value = "/userManagement/loadData.html", ....... produces="text/plain")
//--------because of this-----------------------------------^^^^^^^^^^^^^^^^^^^^^^

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);

Pass array data from javascript in browser to spring mvc controller using ajax

I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX
In javascript, I have
var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;
// how about multiple arrays as well?
$.ajax({
type : "POST",
url : "/myurl",
data : //not sure how to write this, ("a="+a), ?
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
In Java, I would like to create a class to receive data from AJAX, and I create a class to receive data
package com.amazon.infratool.ui;
import lombok.Getter;
import lombok.Setter;
#Setter #Getter
public class RepairInfomationParameters {
//how to write this variable?
List<String> a = null; // is it something like this?
}
What is the correct way to do this? Thanks!
You can do this from the JavaScript side:
$.ajax({
type : "POST",
url : "/myurl",
data : {
myArray: a //notice that "myArray" matches the value for #RequestParam
//on the Java side
},
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
Then on the Java side (in Spring 3), assuming that this method is mapped by /myurl:
public String controllerMethod(#RequestParam(value="myArray[]") Integer[] myArray){
....
}
I believe the following will also work:
public String controllerMethod(#RequestParam(value="myArray[]") List<Integer> myArray){
....
}
Spring is smart enough to figure out how to do the binding.
For multiple arrays, you might want to just have a command object:
public class MyData {
private List<Integer> firstArray;
private List<Integer> secondArray;
private List<Integer> thirdArray;
...
...
}
Then on the JavaScript side:
$.ajax({
type : "POST",
url : "/myurl",
data : {
myData: {
"firstArray": firstArray,
"secondArray": secondArray,
"thirdArray": thirdArray
}
},
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
On the Java side, you can bind using #ModelAttribute:
public String controllerMethod(#ModelAttribute(value="myData") MyData myData) throws ParseException {
....
}
EDIT
Changed the #RequestParam annotation to use myArray[] instead of just myArray, since this change appears to have been made in Spring after this answer was first posted.
It is very simple passing such data to the Spring MVC controller, when you have in mind that data is being parsed from string. So if you want to get an array/list in the controller - pass a stringified version of the array:
public String method(
#RequestParam(value = "stringParam") String stringParam,
#RequestParam(value = "arrayParam") List<String> arrayParam) {
...
}
and the corresponding javascript with jQuery would be like:
$.post("/urlToControllerMethod",
{
"stringParam" : "test",
"arrayParam" : [1, 2, 3, "test"].toString()
}
);
Note: the parameter type
List<String> arrayParam
could be as well replaced with the array equivalent
String[] arrayParam
Vivin Paliath doesn't work unless you use myArray[]
public String controllerMethod(#RequestParam(value="myArray[]") Integer[] myArray){
...
}
If you are using spring mvc 4 then below will be the best approach
Jquery code
var dataArrayToSend = [];
dataArrayToSend.push("a");
dataArrayToSend.push("b");
dataArrayToSend.push("c");
// ajax code
$.ajax({
contentType: "application/json",
type: "POST",
data: JSON.stringify(dataArrayToSend),
url: "/appUrl",
success: function(data) {
console.log('done');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error while post');
}
});
Spring controller code
#RequestMapping(value = "/appUrl", method = RequestMethod.POST)
public #ResponseBody
void yourMethod(#RequestBody String[] dataArrayToSend) {
for (String data : dataArrayToSend) {
System.out.println("Your Data =>" + data);
}
}
check this helps you or not!
Cheers!
Fully tested solution
$.ajax({
type : "POST",
url : "/myurl",
data : {
myArray: a //notice that "myArray" matches the value for #RequestParam
//on the Java side
},
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
#RequestMapping(value = "/save/", method = RequestMethod.POST)
public String controllerMethod(#RequestParam(value="myArray[]") List<Integer> myArray){
System.out.println("My Array"+myArray.get(0));
return "";
}
I end up doing this and it works
In js,
var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;
$.ajax({
type : "POST",
url : "/myurl",
data : "a="+a, //multiple array, just add something like "&b="+b ...
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
java side, get a class to receive data, using lombok
#Setter #Getter
public class MyData {
private ArrayList a;
}
then in the controller
#RequestMapping(value = "/repair_info", method = RequestMethod.POST)
public ModelAndView myControl(MyData myData) {
// get data with myData object
}

Categories