Passing Json object from java script to java - javascript

I am new to springs and ajax
I am having a json object in my java script which is created dynamically
I need to send this json object from java script using ajax or normal submit()
If it is a string we have hidden inputs.
as of my knowledge if I am not wrong
a JSON object we cannot store it in hidden
And I have to receive using java code.
This is my script
$(document).ready(function(){
// click on button submit
$("#save_btn").on('click', function(){
alert();
// send ajax
$.ajax({
url: 'project_reg_save', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#reg_form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
and this is my java code
#Controller
public class Save {
#RequestMapping("/project_reg_save")
public ModelAndView mymethod(#RequestParam JSONObject obj)//which is not possible {
System.out.println(obj);
return new ModelAndView("Product_reg", "msg", "product Registration");
}
}

One solution is to
change your dataType : 'json' to dataType : 'text'
#RequestParam JSONObject obj to #RequestParam String obj
JsonObject JsonObj= new JsonParser().parse(obj).getAsJsonObject();
hence you get json object

Related

Process json object in spring controller

I have this basic quiz app that I'm trying to build and right now I'm stuck on processing the submitted quiz answers in spring.
I use a js function to store the question id and submitted answers id's in a json object like so:
{
1: [2,3,4],
2: [1,2]
}
So, the user sent the answers 2,3,4 for the question with the id of 1. Now, I'm trying to send this json object to the spring controller method using ajax.
// DO POST
function ajaxSubmitAns(formdata){
$.ajax({
type : "POST",
url : "/process-answers",
data: JSON.stringify(formData),
contentType : 'application/json; charset=utf-8',
dataType: 'json',
headers: {
Accept: 'application/json'
},
success: function(){
//do something
},
error : function(e) {
//error
}
});
}
I also wrote the controller function but what I don't know is how do I access these values from the json object. How can I loop through the keys (questions id's) and get the values?
What I have for the controller is this so far:
#RequestMapping(value = "/process-answers", method = RequestMethod.GET)
#SuppressWarnings("unchecked")
public #ResponseBody
String processQuizz(#RequestBody String json) {
}
#PostMapping("/process-answers")
#ResponseBody
public void processQuizz(#RequestBody Map<Integer, List<Integer> quiz) {
quiz.forEach((quizId, answers) -> ... your business logic here ...);
}
Now you can iterate through your map directly without json processing.

MVC5 Controller not receiving JSON Object

I have a controller with method as follows:
public JsonResult Save(List<BlogInfo> list)
{
return Json(new { Data = "" }, JsonRequestBehavior.AllowGet);
}
And I have an ajax post from the client as follows:
$.ajax({
url: "Home/Save",
type: "post",
contentType: "application/json",
data: ko.mapping.toJSON(ViewModel),
success: function (response) {
alert(response.Status);
}
});
My problem is that list parameter to the controller is always null. I tried changing it to string instead of List but that is also null.
Using Fiddler, I can see that the JSON is being pass as follows:
{"Data":[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description","Tags":[]}]}
The JSON you have shown doesn't represent an array, so you cannot possibly expect to bind it to a list on the server. To achieve that make sure that you are sending an array of objects from the client:
data: ko.mapping.toJSON(ViewModel.Data);
Here we take the ViewModel.Data property which represents an array so that we send only the desired JSON:
[{"Id":1,"Title":"Sudoku Solver","Description":"Programmed Sudoku Solver","Tags":["programming","sudoku"]},{"Id":2,"Title":"Picnic","Description":‌​"Went to millpoint","Tags":["picnic"]},{"Id":0,"Title":"Title","Description":"Description‌​","Tags":[]}]

Attempts to use an ajax call to the controller to insert search results into a table result in errors

Longer title would be:
"Attempts to use an ajax call to the controller to insert search results into a table result in errors while remaining on the same page results in "405" or "Direct self-reference leading to cycle... " errors"
I am trying to find a way to fill a table with search result while staying on same page using an ajax call to the controller.
ajaxCall->Controller->Service(completes search)->Controller(result from search)->back to ajax with response
I have an ajax call that is triggered on form submit after prevent default:
function ajaxGetSearchResults(link, form) {
var myList=[];
var jqxhr = $.ajax({
"url" : link,
"data" : form.serialize(),
"dataType" : 'json',
"type" : "POST",
"headers": {
'Content-Type': 'application/json'
},
"success" : function (response){
console.log("Ajax success");
fillTable(response);
console.log("Search results added to table: "+response);
},
"complete": function(response){
console.log("Ajax call to controller completed");
},
"error": function(){
console.log("Ajax call to controller triggered error");
}
});
}
In the controller I recieve the ajax request as such:
#RequestMapping(value = "/ajaxScriptSearch", method = RequestMethod.POST)
public #ResponseBody List<ResultViewDto> processAJAXRequestSearch(#RequestParam String a1,
#RequestParam String a2, #RequestParam String a3, #RequestParam String a4) {
SearchDto searchDto = new SearchDto();
searchDto.setAttribute1(a1);
searchDto.setAttribute2(a2);
searchDto.setAttribute3(a3);
searchDto.setAttribute4(a4);
try {
/*
calling Service, performing search using searchDto as a parameter, mapping result to resultViewDtos
*/
} catch(Exception e){
/* do something */
}
return resultViewDtos;
}
The call to the service is successfull.
An example of resultViewDtos would be: [viewDto1, viewDto2, viewDto3] where every view dto contains a number of string values which need to be inserted into a table.
I seem to be getting a "HTTP Status 405 - Request method 'GET' not supported" error, but my ajax call is "type: POST".
When I tried doing it with GET insted, I get an "Direct self-reference leading to cycle (through reference chain...)" error.
I am using jackson-core 2.6.2, jackson-databind 2.6.2, Spring 4, Hibernate 4.
I would appericiate any help I can get...
In the end I managed to create a workaround for this.
I have changed my ajax call as such:
function ajaxGetSearchResults(link, form) {
var jqxhr = $.ajax({
"url" : link,
"data" : form,
"dataType" : 'json',
"headers": {
'Accept' : 'application/json',
'Content-Type': 'application/json'
},
"type" : "GET",
"success" : function (response) {
console.log("Ajax success");
fillTable(response);
},
"complete": function(response) {
console.log("Ajax call to controller completed");
},
"error": function() {
console.log("Ajax call to controller triggered error");
}
});
}
And my controller as follows:
#RequestMapping(value = "/ajaxScriptSearch", method = RequestMethod.GET)
public #ResponseBody List<String> processAJAXRequestSearch(#RequestParam String a1,
#RequestParam String a2, #RequestParam String a3, #RequestParam String a4) {
SearchDto searchDto = new SearchDto();
searchDto.setAttribute1(a1);
searchDto.setAttribute2(a2);
searchDto.setAttribute3(a3);
searchDto.setAttribute4(a4);
List<String> result = new ArrayList<String>();
List<ResultViewDto> resultViewDtos = new ArrayList<ResultViewDto>();
try {
/*
calling Service, performing search using searchDto as a parameter, mapping result to resultViewDtos
*/
for(int i=0; i<resultViewDtos.size(); i++){
result.add(resultViewDtos.get(i).toResponseString()); //a new method
}
} catch(Exception e){
/* do something */
}
return result;
}
toResponseString() is a new method I have created in my resultViewDto that returns a string in which the attributes I need are separated by ":".
After filling the result and sending it back to ajax as a response, I then split the recieved response first on (',') to get the individual "rows" equivalent to a single resultViewDto, and then by (':') to get the values for each cell.
There might be a better way of solving it, but this woked like a charm.
I hope this will be usefull for someone else too.

Ajax data not getting to controller? why?

I am working with mvc4 application. I developed a form using .cshtml file, which inherits the model and has its corresponding controller action.
I am submitting the form using a ajax jquery like,
var body=$('#formId').serialize();
$.ajax({
url: submitAction,
type: "POST",
datatype: "json",
data: body,
success: function (data) {
if (data != null) {
alert("success");
}
});
"body" is fine and it has serialized data and the submitAction is the var which holds my controller action and the controll is transfered there.
EDIT:
My controller looks like,
public JsonResult(ParentModel model) /*here model always hold null values, WHY??*/
{
//stmts..
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
But, there the parameter of my controller action is showing null values. Can someone tell what could be the mistake and how can I resolve it?
$.ajax({
url: submitAction,
type: "POST", <-- you make post, but asp.net mvc controller receives default GET request
data: { model: body},
[HttpPost]
public JsonResult(string model) //<--now you pass string and to Deserialize in ParentModel
{
JavaScriptSerializer jss= new JavaScriptSerializer();
ParentModel pmodel = jss.Deserialize<ParentModel >(model);
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
Try edit data: section in you request,
remove datatype: "json"
And edit type model parameter to string

string[] via Ajax and ASP.Net (MVC)

my problem is following.
I try to parse some data via ajax, passing the data to my controller:
AJAX
$.ajax({
type: "GET",
url: "ParseOrganizaitonPath",
data: {
organizationPath: $('#organizationPath').val()
},
success:
function (data) {
//data is from type string with value "System.string[]"
//but should be from type System.string[]
});
}
});
Controller
public string[] ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return organizations.ToArray();
}
I am reaching the controller method and in it everything is fine, but the data that is comming back (ajax part, success method) is just a string ("System.string[]", data[0] S, data[1]y data[2]s...) but not the data I want. (For example if i pass the input "test/one" I want to have as result data[0] test, data[1] one)
Hope you understand what my Problem is.
Thanks in advance!
Julian
Have to tried to use the JavaScriptSerializer? Have a look at this example:
public string ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
return oSerializer.Serialize(organizations);
}
To deserialize the JSON string with JavaScript you can use the parse function:
var array = JSON.parse(data);
I found a way where you don't have to serialize it (on c# site) and parse it (on javascript site)
Just use the JSON Method that is inherited from the Controller and return an JsonResult:
public JsonResult ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return JSON(organizations);
}
On the client site (javascript) you have to use JSON.stringfy(dataObject) for data that you want to send to your controller-method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "ParseOrganizaitonPath",
data: JSON.stringify(myDataObject),
success:
function (data) {
//use your data
});
}
});
That's how it worked for me.
Good luck!
Julian

Categories