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.
Related
Am currently working on fullCalendar (jQuery plugin) and now stuck with silly issue but I couldn't overcome it .
Trying populate event details from database on Calendar page load . Here is my code ,
$('#calendar').fullCalendar({
defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
eventSources: [
getEvents()
]
});
function getEvents(){
alert("Inside get Events");
$.ajax({
url : "/FullCal/eventDetails.do",
dataType : 'json',
success : function(data){
alert(data)
}
});
}
Am using Struts framework and here is my action mappings,
<action path="/eventDetails" type="com.struts.action.CalendarInviteAction" >
<forward name="success" path="/Calendar.jsp" />
</action>
And my action class has the event details data in JSON format. My question is how to write the json data into ajax response(In simpler words , how to return the json data to ajax call) . Here is my action class UPDATED
public ActionForward execute(ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response) throws Exception{
System.out.println("TEsting inside getEventDetails");
ArrayList<EventForm> arr = new ArrayList<EventForm>();
arr.add(new EventForm("HandOff Meeting" , new Date(), new Date(),"Meeting at HandOffBridge"));
Gson gson = new Gson();
String jsonString = gson.toJson(arr);
response.getWriter().write(jsonString);
return null;
}
jsonString contains eventDetails in JSON format , how to return this to ajax.
Please help me to achieve this.
Your ajax call seems fine. Just need to display ajax response in proper way.
events: function(start, end, timezone, callback) {
$.ajax({
url : "/FullCal/eventDetails.do",
dataType : 'json',
success : function(data){
callback(data);
}
});
}
A dataType : 'json' is used by [jQuery Ajax][1] to specify a data type that is expected to return by the success callback function when the action and result is executed, and a response returned from the server.
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 URL should correctly point to the action mapping. Assume it will be in the default namespace, otherwise you should modify URL and mapping to add the namespace attribute.
<script type="text/javascript">
$(function() {
$("#dialog-form").dialog ({
autoOpen: true,
height: 500,
width: 750,
modal: true,
buttons : {
"Search" : function() {
$.ajax({
url : '<s:url action="part" />',
success : function(data) {
//var obj = $.parseJSON(data);
var obj = data;
alert(JSON.stringify(obj));
}
});
}
}
});
});
</script>
My first guess is why return null?
return null;
Just return the json string:
return jsonString;
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 );
});
I am trying to pass long array from jquery load to spring controller. How can i sent js object array t spring mvc controller.
Every time action occured the no data alert on script will called.
Script
var arr = [];//Array
$(document).ready(function() {
$(".rating").click(function() {
var idx = $(this).closest('td').index();
var userskill = {//Object
tech : $(this).closest('td').siblings('td.tech').text(),
skill : $('#listTable thead th').eq(idx).text(),
rValue : $(this).val()
}
add(userskill);
});
});
function add(userskill) {
arr.push(userskill);
$.ajax({
type : 'POST',
dataType : 'json',
url : '/SimplWebApp/saveUserRating',
data : ({
id : JSON.stringify(arr)
}),
success : function(responseData) {
if (responseData != null) {
alert(responseData);
} else {
alert("no data");
}
}
});
}
controller
#RequestMapping(value = "saveUserRating")
public #ResponseBody String saveUserRating(#RequestParam(value="id[]", required=false) String[] x) {
Gson gson = new Gson();
String data = gson.toJson(x);
return data;
}
The JSON array resides in the body of the request. You can use the #RequestBody annotation to obtain the array if you have Jackson on the classpath to deserialize the JSON.
saveUserRating(#RequestBody(required=false) String[] ids)
If you want to use the array as the response body simply return the array from the handler method. It will be serialized to JSON automatically.
#ResponseBody
public String[] saveUserRating(saveUserRating(#RequestBody(required=false) String[] ids)) {
return ids;
}
in view somewhere I need to assign value from action which returns json object I would like to assign like below:
<script type="text/javascript">
var jsonFromAction = #Html.Action("GetMenuJson", "Test");
</script>
My Controller Action Code is below:
public ActionResult GetMenuJson(int? subCategoryId)
{
_lCatService = new LeftCategoryService();
List<FlatObject> flatObjects = _lCatService.GetCategory(UIUtility.Uitlity.CurrentLanguageCode);
return Json(GetList(flatObjects, 0), JsonRequestBehavior.AllowGet);
}
make a ajax call :
$.ajax({
type: "Get",
url: 'GetMenuJson',
data: "Test",
success: function (result) {
var jsonFromAction = result;
}
});
and your api's return type should be Json (JsonResult), so that it can return the Json
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