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
Related
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
}
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);
}
My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}
i have created a java webservice to return country list
#RequestMapping(value = "/getcountrylist", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody
#ApiIgnore
Object getcountrylist(#RequestParam String pvtToken,
#RequestParam String lan) {
System.out.println(API_TAG + "Request recevied to get CountryList");
System.out.println("DB:"+dbName);
if (!this.pvtToken.equals(pvtToken)) {
CountryList countryList = new CountryList();
return new ResponseEntity<CountryList>(countryList,
HttpStatus.UNAUTHORIZED);
}
CountryList countryList = avlMobileAPIService.getCountryList(lan);
return new ResponseEntity<CountryList>(countryList, HttpStatus.OK);
}
i need to call the above webservice from javascript as JSONP, i wrote the following javascript code as below
function buttonClick(){
$.ajax({
type: "GET",
dataType: "jsonp",
crossDomain: true,
url: "http://localhost:8080/api/getcountrylist",
data: {pvtToken:"JXku56AE0067YtRUSAZEE",lan:"en"},
Accept: "application/jsonp",
jsonpCallback: function(data, status){
alert('callback');
alert(data);
},
success: function(data, status){
alert('sucess');
},
});
}
Above function call the webservice and returns the list, but shows "invalid label error" on client side.
{"countrylist":[{"countryId":"4","countryCodeAlpha2":"AF","countryCodeAlpha3":"AFG","countryName":"Afghanistan ","isdCode":"93"},{"countryId":"5","countryCodeAlpha2":"AL","countryCodeAlpha3":"ALB","countryName":"Albania ","isdCode":"355"},{"countryId":"6","countryCodeAlpha2":"DZ","countryCodeAlpha3":"DZA","countryName":"Algeria ","isdCode":"213"},{"countryId":"7","countryCodeAlpha2":"AS","countryCodeAlpha3":"ASM","countryName":"American Samoa ","isdCode":"684"}]}
i found in some article it says, the that ajax call expects JSONP , but return JSON data.
What is the solution?
reffer this link
http://www.iceycake.com/2012/06/xml-json-jsonp-web-service-endpoints-spring-3-1/
or try in this simple way
#RequestMapping(value = "/mobile_getcountrylist", method = RequestMethod.GET, produces = {"application/x-javascript"})
#ResponseBody
public Object mobile_getcountrylist( #RequestParam("callback") String jsonpCallback) {
System.out.println(API_TAG + "Request recevied to get CountryList");
CountryList countryList = avlMobileAPIService.getCountryList("en");
//countryList.setJsonCallback(jsonpCallback);
return convertToJsonP(countryList,jsonpCallback);
}
private String convertToJsonP(Object o,String jsonpCallback){
String outputmessage=null;
ObjectMapper mapper = new ObjectMapper();
try {
outputmessage=mapper.writeValueAsString(o);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(outputmessage!=null){
outputmessage=jsonpCallback + "(" + outputmessage + ")";
}
return outputmessage;
}
Javascript code
$.ajax({
type: 'GET',
url: 'http://localhost:8080/api/mobile_getcountrylist',
crossDomain: true,
async: false,
jsonpCallback: 'jsonpCallback',
dataType: 'jsonp',
contentType:'application/json',
success: function(data) {
alert('ok');
}
});
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.