Send jquery data to struts action - javascript

I'd like to send a data from my javascript to my struts action. It's just an id, therefore i wonder if there is a better way than to do it through a form.submit();
here is the variable i'd like to send.
var id = $('[data-detailsid="' + $(this).data('headid') + '"]');
What would be the proper way to do it ?
My current js function :
$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id
});
And my struts action :
#Action("/deleteProduct")
#ResultPath("/")
#Result(name = "success", location = "jsp/board.jsp")
public class DeleteAction {
int productId;
#Autowired
private UserDao userDao;
public String execute() {
Product currentProduct = new Product();
currentProduct.setId(productId);
userDao.deleteProduct(currentProduct);
setProducts(userDao.getProducts());
return "success";
}
public void setProductId(int productId) {
this.productId = productId;
}
}

If you are calling action via Ajax, there isn't necessary to return dispatcher result. You can return result type json if you have json plugin on the classpash and #ParentPackage("json-default") annotation to the action. You can use root parameter to the json result to define the object being serialized when result is executed. By default the root is set to the action instance, so all properties are serialized. If you want to restrict/allow some properties from json serialization you can use parameters to the result excludeProperties and includeProperties. Both parameters are mutually exclusive.
#Result(type="json", params = {"includeProperties", "productId" })
It will return productId back to the page if it was populated to the action bean and the action class has a getter method.
You can get the result on success callback function using
$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id,
dataType: "json"
}).done(function(data){
console.log("The product id:" + data.productId);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});

Related

ODataController converting json to array

This is in continuation with one of the previous questions
I have a OData Controller with the Action as :
[HttpPost]
[ODataRoute("PostUpdate")]
public async Task<string> PostUpdate(HttpRequestMessage eventsToUpdate)
{
//Do something
}
This is how I am calling the controller through the ajax call:
var eventsToUpdate = [];
for(i=0;i<5;i++)
{
//Build the data
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
eventsToUpdate.push(updatedT);
}
Url = "Api/Odata/PostUpdate"
$.ajax({
url :Url,
type:"POST",
data:eventsToUpdate ,
dataType : 'json',
success : function(result) {
}
});
The problem is even after converting an array to json , the data is not available in the controller's action. This is what I did
var eventsToUpdate = JSON.stringify(eventsToUpdate);
But if I just pass
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
I get the same data in action . What is the solution for this?
What seems to me your [HttpPost] is expecting a key named eventsToUpdate but it doesn't find in the posted request as it is not there because of:
data:eventsToUpdate , // which is eq to = data:[{},{}...],
better to send an object like:
data:{eventsToUpdate:eventsToUpdate} ,
//----^^^^^^^^^^^^^^---------this key will be captured at backend
contentType:'application/json', //<------you would need to add this
and another suggestion is to use traditional:true, if required.
Also, async Task<string> if return type is string then you need to change the dataType of the ajax too or you should return json from the WebMethod.

Spring MVC back end ajax validation

For my current project Java/Spring project I have to validate a form. The webpage is a freemarker template file.
The <form> has no special attribute to send the data to the controller. The project uses Ajax to send the request. The controller doesn't receive the form at all.
When the user submits the data, a JavaScript function is called to receive all the data by collecting the elementID's. The data is put in a variable, like this (short version);
var userId = document.getElementById('input_id').value.toLowerCase();
var width = document.getElementById("width");
var height = document.getElementById("height");
The function then puts all the data into a JSON. This JSON is put in the Ajax, and then Ajax calls the right controller.
**Ajax code **
$.ajax({
url: url,
type: "POST",
dataType: "json", // expected format for response
contentType: "application/json", // send as JSON
Accept: "text/plain; charset=utf-8",
"Content-Type": "text/plain; charset=utf-8",
data: data,
success: function (response) {
// we have the response
if (response.status == "SUCCESS") {
console.log("succes");
//Redirect to the right page if the user has been saved successfully
if (type === "setupuser") {
window.location = "/setup/user/" + userId;
} else if (type === "simulatoruser") {
window.location = "/simulator/user/" + userId;
}
} else {
errorInfo = "";
for (i = 0; i < response.result.length; i++) {
errorInfo += "<br>" + (i + 1) + ". " + response.result[i].code;
}
$('#error').html("Please correct following errors: " + errorInfo);
$('#info').hide('slow');
$('#error').show('slow');
}
},
error: function (e) {
alert('Error: ' + e);
}
});
The following controller is called by the Ajax request:
#RequestMapping(method = RequestMethod.POST, value = "/adduser/{userType}")
#ResponseBody
JsonResponse addUserMapping(#ModelAttribute(value="user") User user, BindingResult result, #RequestBody String jsonString, #PathVariable String userType) {
def json = new JsonSlurper().parseText(jsonString)
String userId = json.userId
String userName = json.userName
user.setId(userId)
user.setName(userName)
log.warn("User id..... "+user.getId())
log.warn("User name..... "+user.getName())
JsonResponse res = new JsonResponse();
ValidationUtils.rejectIfEmpty(result, "id", "userId can not be empty.");
ValidationUtils.rejectIfEmpty(result, "name", "userName can not be empty");
if(!result.hasErrors()){
userService.addUser(jsonString)
res.setStatus("SUCCESS");
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
As you can see, Ajax sends a JSON to the controller. The controller unpacks the JSON and puts the data into the user object. Then the user object is being validated using "rejectIfEmpty()" method...
Now I've been reading about making a userValidator class extending Validator, or simply putting Annotations in the bean class like:
#Size(min=1, max=3)
I prefer these annotations since you don't have to write special code for checking certain simple things (like the field not being empty .. #NotEmpty)
But that doesn't work because the controller doesn't take a user object the second it's called, instead it takes the JSON and then unpacks it (Validating is too late..)
TL:DR
Controller takes a JSON as a parameter instead of an Object. The JSON has to be unpacked and then validated in the controller as a java object using rejectIfEmpty as an example. I don't want a full page reload, but I still want to keep Ajax.
BTW: I want to validate the data against more things like regex etc. But the rejectifEmpty is a simple example.
Does anyone have an idea how to handle this?
I fixed the validation by parsing the JSON in the controller and setting it in the user object. The user object is then put in my UserValidator class and validated.
Link for more info using the validator:
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/validation.html

JsonResult returning data, but Jquery Ajax returns undefined data when type is GET

I have a javascript function calling a JsonResult method, and the JsonResult method is sending the data back to the function, but when I test it with an alert in the javascript function it returns as Undefined. I have checked out a couple similar answers on SO, like this JsonResult returns null for Jquery .ajax and Jquery ajax not returning data [duplicate] but they are dealing with POST and not GET, can I get some guidance on what I am doing wrong or direction to where I can this figured out?
The end result is I need to get all the returned data from the JsonResult method then populate it into textfields.
My JsonResult method is..
public JsonResult myResult(string id)
{
dal = new AWDAL();
List<CustomerToAdd> cust = dal.GetCustomerByID(id);
return Json(cust, JsonRequestBehavior.AllowGet);
}
and my JavaScript is this..
function DataToGet(whatever) {
alert(whatever.customerName);
}
function GetCustomerByCustomerID() {
//var id = selectCustomerID;
var result = "";
$.ajax({
type: "GET",
url: "#Url.Action("myResult", new { id = "1234-5678-9012" })",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
return DataToGet(data);
}
});
}
I found this way of doing what I want but its for WebAPI2, I am not using WebAPI2 but it looks better, I am not even sure if I can use it to do what I want.
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
function find() {
var id = $('#prodId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#product').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#product').text('Error: ' + err);
});
}
EDIT
Response Header
Response Body
The payload is an array. To get a single item in the payload you would need to get it like so data[0] and each field data[0].customerName.

Ajax call not reaching controller method

Yes, there are a whole bunch of posts with similar questions. I've tried to follow the answers in them, but my ajax call still isn't reaching the controller method.
controller (SalesController.cs):
[HttpGet]
public JsonResult fillVarietiesSelect(int species_id)
{
String[] alist = {"a","b","c"};
return Json(alist, JsonRequestBehavior.AllowGet);
}
javascript:
$('#species-select').on('change', function () {
var species_id = $('#species-select').val();
console.log("species id selected " + species_id);
alert("species id selected " + species_id);
$('#variety-select').empty();
$.ajax({
type: 'GET',
url: '#Url.Action("fillVarietiesSelect", "Sales")',
data: {species_id : species_id},
success: function (result) {
alert(result);
}
});
});
The on change event is firing, and the alert pops up with the correct data. I have a breakpoint set at the controller method, but execution doesn't seem to get there.
try doing exactly like following
Controller:
[HttpGet]
public ActionResult receive2(string p)
{
ViewBag.name = p;
List<string> lst = new List<string>() { p };
return Json(lst,JsonRequestBehavior.AllowGet);
}
Client side
$.ajax({
type: "GET",
url: "Main/receive2", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { "p": $("#txtname").val() },
dataType:"json",
success: function (result) {
alert("yes");
alert('Yay! It worked!tim' + result);
window.location = "http://google.com";
// Or if you are returning something
},
error: function (result) {
alert('Oh no aa :(' + result[0]);
}
});
I have checked it's working
I had the same issue, changing the parameter from int to string resolved the problem.
On the server side I had,
public string RemoveByDocumentID(int DocumentID)
changing that to
public string RemoveByDocumentID(string DocumentID)
resolved the issue.
On the same context, I have another method in the same name (overloaded method). Which was also contributing to the issue, so I made the method name unique.
Your 404 error is telling you that #Url.Action is not being parsed by the view engine. The # is Razor syntax, so for this to work you need to be using a .cshtml extension for C# views or .vbhtml for VB views and be using MVC 3 or above.

success method not fire on Ajax call

When I ran below code for bttn click event it doesn't return a data for success method.
But it goes for controller method and return false (boolean value) as a out put.I need to pick that boolean value from javascript code.
Why it doesn't work ?
Javascript code is as below:
$('#btnClockInTime').off('click').on('click', function () {
var isClockOutTimeCompleted = true;
$.ajax({
url: "/Employees/IsClockOutTimeCompleted",
type: "GET",
dataType: "json",
cache: false,
data: { employeeId: employeeId },
success: function (data) {
if (!data) {
isClockOutTimeCompleted = data;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
Controller Action Method is as below:
[HttpGet]
public JsonResult IsClockOutTimeCompleted(Guid employeeId)
{
var clockingDate = Convert.ToDateTime(DateTime.Today);
var isClockOutTimeCompleted = Repository.IsClockOutTimeCompleted(employeeId, clockingDate);
return Json(isClockOutTimeCompleted, JsonRequestBehavior.AllowGet);
}
Repository code is as below:
public bool IsClockOutTimeCompleted(Guid employeeId, DateTime clockingDate)
{
var clockOutTime = (from c in Catalog.EmployeeClockInOutTimes
where (c.Employee.Id == employeeId && c.Created == clockingDate && c.ClockOut == null)
select c).FirstOrDefault();
return clockOutTime == null;
}
UPDATE :
Response is as below :
UPDATE 2 :
Screen 1 :
Screen 2 :
Screen 3 :
As shown above images my debug doesn't come into success method.
After 2nd screen (when debug at error) it goes to controller and brings data.
3rd screen shows a status after returning from controller.Any idea ?
I would have thought that if you're return value is just false as a string then that will become your data value and as a result:
if (!data) { // won't fire }
As Darin says, if you wrap up your response Json inside an object and then use that to assign to your isClockOutTimeCompleted variable.
I wouldn't have thought you'd want to perform a boolean evaluation of your return value if it's a true/false return type, wouldn't you just want to assign it to isClockOutTimeCompleted either way?
if ur posting data to a controller method always use
'type':'POST' in ur ajax call &
change the [HTTPget] attribute from ur controller method to [httpPost]
below is my sample code which works fine
$.ajax({
url: 'Home/temp',
type: 'POST',
dataType: "json",
data: {'name':'surya'},
success: function (data) {
console.log(data);
//here i'm getting the data which i have passed
},
error: function () {
console.log("inside error")
}
});
and my controller code
[HttpPost]
public JsonResult temp(string name) {
return Json(name);
}
i'm getting back the data which i have passed in to the controller method via my jquery ajax..
may be u ought to change ur 'IsClockOutTimeCompleted' method where u are performing linq queries.just validate ur linq queries once..and also employeeId which ur passing into the controller is of type integer then instead of GUID as a parameter why dont u change the parameter type as int and see..
Regards

Categories