Ajax call to spring controller callback error function - javascript

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

Related

How to pass ajax into a spring controller

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

Error in ajax request

I try to send ajax request in my SpringMVC project.
$.ajax({
contentType : 'application/json; charset=utf-8',
type : 'get',
url : 'order/get/'+i,
dataType : 'json',
data : {},
success : function(result) {
alert("Successfully!");
},
error : function(result, status, er) {
alert("error: "+result+" status: "+status+" er:"+er);
}
});
#RequestMapping(value = "/order/get/{id}", method = RequestMethod.GET)
public ResponseEntity<Order> getOrder(
#PathVariable("id") long id) {
Order order = orderService.getOrderById(id);
if (order == null) {
new ResponseEntity<Order>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Order>(order, HttpStatus.OK);
}
But I always get error.
In controller method return object of 'order', but ajax throws 'GET net::ERR_CONNECTION_RESET'.
Why ?
The problem was that the Order entity serialized to JSON with all the attributes, including those that marked as #ManyToOne. This serialization Json was excessive, and the response was very huge. The entity class Order, had to designate attributes such annotation #JsonIgnore. After this error is gone and the answer is processed normally.

Call a different Controller action from view of a controller though javascript

I have a Home controller whose view has a button.I want to call a controller named SearchSpace on button click.
View :
<script type="text/javascript">
var data = { "id": "1" }
function search() {
alert("hello" + JSON.stringify(data));
$.ajax({
url: '/SearchSpace/searchSpace',
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(data),
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
}
});
}
</script>
Controller
[HttpGet]
public ActionResult searchSpace()
{
return View();
}
[HttpPost]
public ActionResult searchSpace(SearchSpace search)
{
//code
return View();
}
Route Config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
alert is calling but it is not moving to SearchSpace Controller..
Please help me.
try this
<button id="click">Click me
</button>
Problem is with data type that jQuery.ajax() is expect, since you assign dataType property with json. From jQuery API documentation:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
..."json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
There are at least 2 ways to solve the problem:
First, Omit dataType property:
$.ajax({
url: '/SearchSpace/searchSpace',
type: 'POST',
contentType: 'application/json',
//dataType: "json", << delete this line or comment it
data: JSON.stringify(data),
success: function (data) {
console && console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
}
});
Second, return JSON type data from response:
[HttpPost]
public ActionResult searchSpace(int? id)
{
if (Request.IsAjaxRequest() && id != null)
{
return Json(new { data = "Requested data is: " + id.ToString() });
}
return View();
}

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

How to get data from ajax call?

I am trying to get data from ajax call by cross domain.
Here is code
function GetMaxWULen() {
var x;
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).done(function(result) {
console.log('done result');
x = result;
console.log(x);
});
console.log('function end');
console.log(x);}
At the end of the function, x variable is undefined but in done event value is correct.
Could anyone can help me or tell what is wrong in this code?
This happens because your AJAX request is done asynchronously. It means the rest of your code won't wait your response be ready to continue.
If you need to use the data returned from AJAX outside your function, you might want to create a parameter to serve as a callback when the response is ready. For example:
function yourFunction(callback) {
$.ajax({
/* your options here */
}).done(function(result) {
/* do something with the result here */
callback(result); // invokes the callback function passed as parameter
});
}
And then call it:
yourFunction(function(result) {
console.log('Result: ', result);
});
Fiddle: http://jsfiddle.net/9duek/
try
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).success(function(result) {
var datareturned = result.d;
console.log('done' + datareturned);
x = datareturned;
console.log(x);
});

Categories