JSON Error in retrieving data - java

Here is Client side code:
function startAjax() {
$.ajax({
type : 'GET',
url : 'customers/ShowAllCustomers',//this is url mapping for controller
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
success : function(response) {
alert(response.get(0).first_name);
//this response is list of object commming from server
},
error : function() {
alert("opps error occured");
}
});
}
and here is my Controller:
#RequestMapping(value="/ShowAllCustomers", method = RequestMethod.GET)
public #ResponseBody List<Customer> AllCustomersList() {
List<Customer> customers= customerService.getAllCustomers();
return customers;
}
Everytime "oops error occured" alert appears. Can you please point out error in this for me. I will be really thankful......

List<Customer> customers= customerService.getAllCustomers();
return customers;
The above code returns a Java List , but the jQuery is expecting a JSON String .
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
You need to convert the List to a JSON string using some JSON library.

Related

Error javax.json.stream.JsonParsingException: when making an AJAX API call

I have developed a web based program using java jersey in my back end and jsp in my front end. When I make a post API call using Ajax my back end gets the following exception.
javax.json.stream.JsonParsingException: Unexpected char 117 at (line
no=1, column no=1, offset=0)
I guess it's something wrong with the data which I'm passing through the Ajax API call.
Here is my ajax API call:
var obj = JSON.parse('{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}');
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: obj,
dataType: 'json',
success: function () {
alert("successed");
}
});
This is my back end implemented code:
#Path("testing")
public class test {
UserRepository userRepo=new UserRepository();
#Path("users")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public UserModel CreateUser(UserModel a) {
userRepo.createUser(a);
return a;
}
}
You should send the data as a JSON String, not a JSON Object. Avoid the JSON.parse from your code.
var data = '{ "userName":"John", "password":"hgvv", "img":"New York","fname":"kjbjk","lname":"bkbkkj","tp":"buhb","address":"jhbjhb","type":"user"}';
Alternatively, I would construct the JS Object, and apply JSON.stringify on it. This way, the code is more readable:
var data = {
userName: "John",
password: "hgvv",
img: "New York",
fname: "kjbjk",
lname: "bkbkkj",
tp: "buhb",
address: "jhbjhb",
type: "user"
};
$.ajax({
type: "POST",
url: $url,
contentType: "application/json",
data: JSON.stringify(data), // added JSON.stringify here
dataType: 'json',
success: function () {
alert("successed");
}
});

return new ModelAndView doesnt work

My controller :
#RequestMapping(value="/testAdmin", method = RequestMethod.POST,consumes = "application/json")
public ModelAndView testAdmin(#RequestBody Student student) {
System.out.println(student.getName()+" "+student.getId()+" "+student.getLogin()+" "+student.getPassword());
return new ModelAndView("showString","student",student.getName());
}
My ajax function:
function test2(a,ob) {
var student={
id:ob[a].id,
login:ob[a].login,
password:ob[a].password,
name:ob[a].name
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
url: "testAdmin",
data: JSON.stringify(student),
success: function (response)
{
alert("success");
},
error : function(xhr, status, errorThrown) {
alert(status+" "+errorThrown.toString());
}
});
}
Controller method works, but it doesnt go to other page.
I dont know how to fix it, give an example or information to read

Retrieve array containing name value pair from ajax request in spring mvc

I'm unable to retrieve the 'values' in my Spring Controller. Can anyone explain what I am doing wrong?
Ajax request
fields[fieldID] = { 'name': fieldName, 'value': fieldValue };
fieldID++;
$.ajax({ url: '/lic/register.html',
data: { 'send': 'login-form', 'values': fields},
type: 'get',
complete : function(){
alert(this.url)
},
success: function( output ) {
alert("success");
},
});
Spring controller
#RequestMapping(value="/register.html", method = RequestMethod.GET)
#ResponseBody
public String suckRegister(HttpServletRequest request,HttpServletResponse response,#RequestParam(value="values", required=false) String[] objectValues) {
System.out.println(objectValues.length); // returning null
}
seems there isn't any need for 'send': 'login-form', unless another request param accepting that value in your controller
Try,
$.ajax({ url: '/lic/register.html',
data: { 'values': fields},
type: 'get',
dataType: "json",
contentType: "application/json",
complete : function(){
alert(this.url)
},
success: function( output ) {
alert("success");
},
});
And your controller should accept
#RequestMapping(value="/register.html", method = RequestMethod.GET)
#ResponseBody
public String suckRegister(HttpServletRequest request,HttpServletResponse response,#RequestParam(value="values[]", required=false) Object[] objectValues) {
System.out.println(objectValues.length); // returning null
}

how can I send and retrieve params in spring?

I am triyng to do a simple thing, with ajax, send a request (using a GET, or POST).
I will be sending 2 parameters in a json format , and I just want to get them back and send a response, still, I always get an error 400 and others that I dont know whats wrong, any idea how?
I started based on this article: http://fruzenshtein.com/spring-mvc-ajax-jquery/
I am using spring mvc.
So far I have this:
$(".update_agent").live('click', function(){
var agent = { "agentId" : agentID, "hostAGent" : hostID};
//send ajax
$.ajax({
url: url,
data: JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
})
and at my java controller I have this
#RequestMapping(value = "/update", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public int updateAgent(HttpServletRequest req, HttpServletResponse res) throws IOException{
req.getParameterValues("agentId");
return AGENT_UPDATE_SUCCESS;
}
But I cant get it back, have no idea how to make the request of the params, any idea?
Thanks.
=====================UPDATE============================
Ive changed the code and this how it looks like...
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: 'POST',
url: url,
data: JSON.stringify(agent),
dataType: 'json',
success:function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
And at my controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public #ResponseBody Integer updateAgent(#RequestBody String param) throws IOException{
System.out.println(param);
//do something...
return 1;
}
the problem is that I am getting an error 415, unsupported media type, any advice?
GET-request can not have 'data'-field. You need to send your data as part of the url:
$.ajax({
url: url + "?agent=" + JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
now you can get the data in your controller as:
#ResponseBody public ResponseEntity<String> updateAgent(#RequestParam(value = "agent") String agentJson){
...
}
or you can send a POST-request. With a POST-request you can send your data as requestBody:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody String agentJson){
...
}
EDIT:
create a new Agent-class:
public class Agent {
private long agentId;
private long hostAgent;
...
getter and setter
...
}
now update the controller to:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody Agent agent){
System.out.println(agent.getAgentId());
}
and change the "Content-Type" of ajax-call to "application/json".
EDIT2:
change your ajax-call data to:
data: { agentId: agentID, hostAgent : hostAgentID} ,
or even
data: agent ,
Don't forget to change "hostAGent" to "hostAgent" in your agent object, or you will get 400!!!
now ajax will send the data as request parameters, you can get the data in your controller by:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestParam(value = "agentId") long agentId, #RequestParam(value = "hostAgent") long hostAgentId){
System.out.println(agentId);
}

Send json object with another parmeter to the controller in spring mvc

1.- I want to recive this two paramters like this in my controller :
*/Controller
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST)
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
String table_name = tableName;
String catalogInserted = catalogGenericService.insertCatalogGeneric( table_name, catalogGeneric);
return catalogInserted;
}
2.- I send to the contoller in this way...
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: {'catalogGeneric' : JSON.stringify(description_data) , 'tableName' : "fadsf"},
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
3.- In my debug I receive error 400 not found the direction .... i know that is for the way that i send the parameters , but what will be the correct form to do that ?
In your case, Ajax call having contentType: "application/json" format, So when your doing ajax call with JSON format, In your Controller your Request Mapping should have consumes = "application/json",
For the particular request mapping add like this in your controller,
#RequestMapping(value = "/insertCatalogGeneric", method = RequestMethod.POST,
consumes = "application/json")
public #ResponseBody
String insertCatalogGeneric(#RequestBody CatalogGeneric catalogGeneric , String tableName) {
[Additional]
For safe request body format
try to stringify the whole JavaScript Object.
$.ajax({
url : 'insertCatalogGeneric',
type : 'POST',
data: JSON.stringify({'catalogGeneric' : description_data , 'tableName' : "fadsf"}),
cache: false,
contentType: "application/json; charset=utf-8",
success:function(data, textStatus, jqXHR) {
}
});

Categories