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
}
Related
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
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);
}
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) {
}
});
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'm trying to send json data to servlet using ajax jquery call... below is the code
$(function() {
$( "#mybutton").click(function() {
var testdata = JSON.stringify({
'name': 'name',
'desc':'test'
});
$.ajax({
type: "POST",
url:"/Alert/ReportServlet",
data: testdata,
dataType: "json",
contentType: "application/json",
success : function(data){
console.log("success:", data);
},
error : function(data) {
console.log("error:", data);
}
});
});
});
and the servlet code is
public class ReportingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
System.out.println("The data is" + request.getParameter("testdata"));
}
}
The value is coming as null...Please suggest
In servlet try with
request.getParameter("name");
request.getParameter("dest");
In your Ajax call do something like this
$(function() {
$( "#mybutton").click(function() {
var testdata = JSON.stringify({
'name': 'name',
'desc':'test'
});
$.ajax({
type: "POST",
url:"/Alert/ReportServlet",
data: { d : testdata },
dataType: "json",
contentType: "application/json",
success : function(data){
console.log("success:", data);
},
error : function(data) {
console.log("error:", data);
}
});
});
});
then in java try :
request.getParameter("d");
this you can use some library (like jackson) to convert d into HashMap