$.ajax to send data vis HttpPost in aspnet5 is not working - ajax

this is a followup question to the one here Using $.ajax to send data via HttpPost in aspnet5, is not working
I have made the changes requested in the comments and a few other changes such as using the Json package from Newtonsoft.
Basically I have a column, and when you click the header a couple of input tags appear dynamically, to change column name and submit it. I want to change it and show it right away using ajax. The code to do this is below, and sorry but the code is in coffee script. Also I am using ASPNET5 RC1 with MVC6.
SumbitColumnForm = () ->
$('.panel-heading').on 'click', 'input.ColumnTitleSumbit', (event) ->
event.preventDefault();
columnName = $('.NewColumnName').val().trim()
columnNumber = $(this).parent().parent().attr 'id'
$.ajax
url: '/Board/ChangeColumnName',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ColumnName: columnName, ColumnNumber: columnNumber})
success: (data) ->
alert "Hit the Success part"
alert 'data is' + data
panelHeading = $('input.ColumnTitleSubmit').parent()
$(panelHeading).html("<h3 class='panel-title'> <h3>").text(data)
error: (xhr, err) ->
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
The relevant action methods from the controller are below
[Route("{p_BoardName}")]
public IActionResult Show(string p_BoardName)
{
m_Board.BoardName = p_BoardName;
ViewData["BoardName"] = m_Board.BoardName;
return View(m_Board);
}
[HttpPost]
public JsonResult ChangeColumnName(string newColumnData)
{
ColumnModel column = JsonConvert.DeserializeObject<ColumnModel>(newColumnData);
// Update column name in the board model, the board model stores a list of columns
m_Board.ColumnList[column.ColumnNumber].ColumnName = column.ColumnName;
var json = JsonConvert.SerializeObject( m_Board.ColumnList[column.ColumnNumber]);
return Json(json);
}
Also the column and board models are below
public class ColumnModel
{
private string m_name;
private int m_columnNumber;
public int ColumnNumber { get { return m_columnNumber; } set {m_columnNumber = value;} }
public string ColumnName { get { return m_name;} set { m_name = value; } }
public ColumnModel(string p_Name, int p_ColumnNumber)
{
m_name = p_Name;
m_columnNumber = p_ColumnNumber;
}
public ColumnModel() { }
}
public class BoardModel
{
private string m_BoardName;
private List<ColumnModel> m_ColumnList;
[Required]
public string BoardName { get { return m_BoardName; } set { m_BoardName = value; } }
public List<ColumnModel> ColumnList
{
get { return m_ColumnList; }
set { m_ColumnList = value; }
}
}
I have done a lot of googling and I still can't get this to work. The request is not hitting the success attribute and is hitting the error attribute. I still get a 200 status code to show it is OK, and for some reason my data is a long html file, or in this case the 'Show' view from the board controller. I have requested requested Json and I am getting html. I don't know what is going on, I feel what might be going wrong is the http post method ChangeColumnName in the controller. Maybe I am not receiving or sending a valid JSON object. Any help will be greatly appreicated.

The key here is [ValidateInput(false)]
Try this :
Rather than sending a JSON.stringify, just send it as an object which means
var Data = {ColumnName: columnName, ColumnNumber: columnNumber};
You were already doing this from your link!
Change your signature to receive your ColumnModel directly rather than a string and add the attribute [ValidateInput(false)] to your action. You'll not need to deserialize with this approach!
[ValidateInput(false)]
public JsonResult ChangeColumnName(ColumnModel newColumnData)
{
Console.WriteLine(newColumnData.ColumnName);
}
Let me know if this solves your problem!

You are supplying the correct variable
in ajax
data: {ColumnName: columnName, ColumnNumber: columnNumber}
In controller
[HttpPost]
public JsonResult ChangeColumnName(string ColumnName, int ColumnNumber)
{
..your code..
}
hope this helps

Related

ModelState validation fails for nullable types

Can't pass ModelState validation in WebApi application for object which contains nullable types and has null values. The error message is "The value 'null' is not valid for DateProperty."
The code of object:
public class TestNull
{
public int IntProperty { get; set; }
public DateTime? DateProperty { get; set; }
}
Controller:
public class TestNullController : ApiController
{
public TestNull Get(int id)
{
return new TestNull() { IntProperty = 1, DateProperty = null };
}
public HttpResponseMessage Put(int id, TestNull value)
{
if(ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.OK, value);
else
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (var keyValue in ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
}
Request:
$.getJSON("api/TestNull/1",
function (data) {
console.log(data);
$.ajax({
url: "api/TestNull/" + data.IntProperty,
type: 'PUT',
datatype: 'json',
data: data
});
});
I just did a quick test in one my own WebAPI projects and passing null as a value for a nullable value-type works fine. I suggest you inspect the actual data that is being send to your server using a tool like Fiddler
Two valid scenarios that will work are:
{ IntProperty: 1, DateProperty: null }
{ IntProperty: 1 } // Yes, you can simply leave the property out
Scenarios that will NOT work are:
{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer
If the two default scenario's do not work then I suspect your problem lies elsewhere. I.e. Have you changed any of the default settings of the JSON serializer in your global.asax?
Almost 9 years later I'm still having similar problem in ASP.NET Core 3.1
But I've found a working workaround for me (just exclude null values from data being sent - as opposed to sending values as nulls).
See https://stackoverflow.com/a/66712465/908608
It's not a real solution, becasue backend still does not handle null values properly, but at least ModelState validation does not fail for nullable properties.

STRUTS2 and AJAX - Select the country, populate the States

I want to show the states after selecting the country.
JSP
<s:select label="COUNTRY" name="summaryData.addressCountry" id="addForm_countryCode"
list="loyaltyCountryMap" tabindex="" headerKey="US" headerValue="United States"
listKey="key" listValue="value.countryName"
onchange="getStateList('#addForm_countryCode')">
</s:select>
<s:select label="STATE" name="summaryData.addressCityCode" headerValue="-Select-" headerKey="-Select-" list="stateList" required="true" cssClass="storedPaymentInput_size1 required" id="stateList"/>
JAVASCRIPT:
function getStateList() {
var countryCode = $('#addForm_countryCode").val();
$.ajax({
url: 'ajaxStateList',
dataType: 'html',
data: { countryCode : countryCode},
success: function(data) {
$('#stateList').html( data );
}
});
}
STRUTS.XML
<action name="ajaxStateList" class="actions.AjaxStateList">
<result name="success"/>
</action>
ACTION CLASS
private List<String> stateList;
private String countryCode;
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public List<String> getStateList() {
return stateList;
}
public void setStateList(List<String> stateList) {
this.stateList = stateList;
}
public String execute() {
LoyaltyStateProvinces.getInstance();
stateList = StateProvinces.getAllStateProvinceByCountryCode(countryCode);
for(StateProvince state: states){
stateList.add(state.getStateProvinceCode());
}
return SUCCESS;
}
How can I make it work using AJAX+Struts2?
See struts2-json-plugin. Have your actions return a json result type (via this plugin). Your action class can remain largely unmodified.
Once you have created and tested that your action returns JSON (just enter the url in your browser). Then you need some javaScript. I see you are using jQuerys $.ajax method... I prefer the $.getJSON which does the same but assumes the data in a json format.
Here is some js from my own code:
function punch(){
$.getJSON("<s:url namespace="/timeclock/json" action="punch"/>",
{
badge: $("#input_badge").val()
},
function(data) {
$("#input_badge").val("");
$("#emp_name").text(data.name);
$("#emp_time").text(data.punch);
$("#notification").fadeIn("slow", hide);
});
return false;
}
You'll notice three parameters: Fist being the url for the call which is always best constructed with the sturts2 url tag. Second being the parameters being sent to the action, in this case "badge" is set to what ever was in the text field with the id of "input_badge" and then sent to the server. Finally the function which is called when the call back succeeds, you can see parameters such as "name", "punch" are returned.

How to format a JQuery GetJSON

I'm calling the server with:
var url = '#Url.Action("GetWhoBowls", "Home")';
$.getJSON(url, { "theDate": "calEvent.start" }, function (data) {
alert(data.name);
});
I've tried all permutation of quoting the 'theDate' and even calEvent.start as above .... in all cases the server complains that (from Firebug):
The parameters dictionary contains a null entry for parameter 'theDate' of non-nullable type 'System.Double' for method 'System.Web.Mvc.ActionResult GetWhoBowls(Double)' in 'MatchClubMVC.Controllers.HomeController'.
Firebug shows the parameters of the call as
theDate calEvent.start
Here is my controller method signature
public ActionResult GetWhoBowls(double theDate)
Could someone be so kind as to set me on the correct path?!
If you expect a double on your controller don't send a string (remove the simple quotes around calEvent.start otherwise you are sending this string literal to the server which obviously cannot be converted to double):
$.getJSON(url, { theDate: calEvent.start }, function (data) {
alert(data.name);
});
Also make sure that calEvent.start is a valid double value.
try
public ActionResult GetWhoBowls(double? theDate)
also the error is arising because you are sending a null value in { "theDate": "calEvent.start" }
EDIT
not sure whether this will solve the problem or not but try this
var url = '#Url.Action("GetWhoBowls", "Home")';
$.getJSON(url, { theDate: "calEvent.start" }, function (data) {
alert(data.name);
});
and modify the action result like this
public ActionResult GetWhoBowls(double theDate)
{
return(data,JsonRequestBehavior.AllowGet);
}
this will give the same errorif you send null from client

Backbone.js REST URL with ASP.NET MVC 3

I have been looking into Backbone.js lately and i am now trying to hook it up with my server-side asp.net mvc 3.
This is when i discovered a issue. ASP.NET listens to different Actions, Ex: POST /Users/Create and not just POST /users/. Because of that, the Model.Save() method in backbone.js will not work.
How should we tackle this problem? Do i have to rewrite the Backbone.Sync?
The answer is not to override Backbone.sync. You rarely would want to do this. Instead, you need only take advantage of the model's url property where you can assign a function which returns the url you want. For instance,
Forum = Backbone.Model.extend({
url: function() {
return this.isNew() ? '/Users/Create' : '/Users/' + this.get('id');
}
});
where the url used for a model varies based upon whether the model is new. If I read your question correctly, this is all you need to do.
You either have to tell ASP.NET MVC to route proper REST urls or fix Backbone.sync so it sends the GET/POST requests at the proper URLs.
Backbone works with REST not with RESTful URLs. There may be an OS implementation of Backbone.sync that matches your urls though.
Recommend URLs that play more nicely with Backbone:
GET /forums -> index
GET /forums/new -> new
POST /forums -> create
GET /forums/:forum -> show
GET /forums/:forum/edit -> edit
PUT /forums/:forum -> update
DELETE /forums/:forum -> destroy
I wrote a blog post recently describing how to bind .NET MVC to the default Backbone service layer.
Like previous posters have mentioned, there are a number of approaches you could take. I prefer this approach because it requires little configuration.
The controller:
public class ZocController : Controller
{
public ActionResult Docs()
{
return Json(GetDocs(), JsonRequestBehavior.AllowGet);
}
[ActionName("Docs")]
[HttpPost]
public ActionResult HandlePostDoc(Doctor doc)
{
doc.id = Guid.NewGuid();
CreateDoc(doc);
return Json(doc);
}
[ActionName("Docs")]
[HttpPut]
public ActionResult HandlePutDoc(Doctor doc)
{
UpdateDoc(doc);
return new EmptyResult();
}
[ActionName("Docs")]
[HttpDelete]
public ActionResult HandleDeleteDoc(Guid id)
{
DeleteDoc(id);
return new EmptyResult();
}
}
The Backbone
window.Doctor = Backbone.Model;
window.Doctors = Backbone.Collection.extend({
model: Doctor,
url: '/zoc/docs'
});
i found the following code in https://github.com/sgentile/BackboneContacts
/// <reference path="backbone.js" />
ModelBase = Backbone.Model.extend({
defaults: {
id: null
},
url: function (type) {
//expecting the following conventions on the server:
//urlRoot should be the controller : controller/
//create → POST /action
//read → GET /action[/id]
//update → PUT /action/id
//delete → DELETE /action/id
var fqUrl = this.urlRoot;
switch (type) {
case "POST":
fqUrl += "create";
break;
case "PUT":
fqUrl += "update";
break;
case "DELETE":
fqUrl += "delete/" + this.get('id');
break;
case "GET":
fqUrl += "read/" + this.get('id');
break;
}
return fqUrl;
}
});
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
// Helper function to get a URL from a Model or Collection as a property
// or as a function.
var getUrl = function (object) {
if (!(object && object.url)) return null;
return _.isFunction(object.url) ? object.url() : object.url;
};
// Throw an error when a URL is needed, and none is supplied.
var urlError = function () {
throw new Error('A "url" property or function must be specified');
};
Backbone.sync = function (method, model, options) {
var type = methodMap[method];
options.url = _.isString(this.url) ? this.url : this.url(type);
// Default JSON-request options.
var params = _.extend({
type: type,
dataType: 'json'
}, options);
// Ensure that we have a URL.
if (!params.url) {
params.url = getUrl(model) || urlError();
}
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? { model: params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function (xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Don't process data on a non-GET request.
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
// Make the request.
return $.ajax(params);
};

Jqgrid spring date binding exception

OS: Windows Vista, Framework: Jqgrid (latest), Spring (latest), JQuery (latest)
I am using Jqgrid to post a form to Spring Controller to persist. When the Spring controller tries to auto bind the request parameters to domain object, it throws exception when trying to bind 'Date' data type. I am using JSon format for transfer data. The Jqgrid display the date correctly. The transfer string contains '&-quot;' characters before and after the date that causes the exception. I dont know how to remove the escape character from Jqgrid. I dont know how to intercept the string before Spring gets a chance to auto bind. Thanks for your help in advance.
public class JsonDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
AtOverride
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
My controller class has initBinder method.
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
Exception stack trace
nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "2010-12-01 11:10:00" from type 'java.lang.String' to type 'java.util.Date'; nested exception is java.lang.IllegalArgumentException]
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:820)
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:359)
I will try to set-up a tutorial on my blog if I get the time today.
My JSP file is just a simple JSP file with your typical JqGrid declaration:
<script type="text/javascript">
jq(function() {
// This is the grid
jq("#grid").jqGrid({
url:'/myapp/users',
datatype: 'json',
mtype: 'GET',
colNames:['Id','Username','First Name'],
colModel:[
{name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10},hidden:true},
{name:'firstName',index:'firstName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}, editrules:{required:true}},
{name:'lastName',index:'lastName', width:80, align:"right",editable:true, editrules:{required:true}, editoptions:{size:10}, editrules:{required:true}}
],
postData: {
// Here you can post extra parameters
// For example using JQuery you can retrieve values of other css elements
},
rowNum:10,
rowList:[10,20,30],
height: 200,
autowidth: true,
rownumbers: true,
pager: '#pager',
sortname: 'id',
viewrecords: true,
sortorder: "asc",
caption:"Users",
emptyrecords: "Empty records",
loadonce: false,
loadComplete: function() {
// Here you can provide extra functions after the grid is loaded completely
// Like auto-height function
},
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "cell",
id: "id"
}
});
// This is the pager
jq("#grid").jqGrid('navGrid','#pager',
{edit:false,add:false,del:false,search:true},
{ },
{ },
{ },
{
sopt:['eq', 'ne', 'lt', 'gt', 'cn', 'bw', 'ew'],
closeOnEscape: true,
multipleSearch: true,
closeAfterSearch: true }
);
// Custom Add button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Add",
buttonicon:"ui-icon-plus",
onClickButton: addRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Custom Edit button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Edit",
buttonicon:"ui-icon-pencil",
onClickButton: editRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Custom Delete button on the pager
jq("#grid").navButtonAdd('#pager',
{ caption:"Delete",
buttonicon:"ui-icon-trash",
onClickButton: deleteRow,
position: "last",
title:"",
cursor: "pointer"
}
);
// Toolbar Search
jq("#grid").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : true, defaultSearch:"cn"});
});
Take note I'm using JQuery's noConflict method here. Since I have another Javascript framework that uses the $, I forced JQuery to use a different identifier for itself. I picked jq and here's the declaration:
<script type="text/javascript">
var jq = jQuery.noConflict();
</script>
The Javascript's above can be declared on the head section of your JSP. The critical part of the JqGrid declaration is the jsonReader and the datatype. Make sure the colModel name matches your model properties.
You could probably use StringTrimmerEditor's second constructor to delete those extra chars
StringTrimmerEditor(String charsToDelete, boolean emptyAsNull)
Based on the Spring docs:
charsToDelete - a set of characters to delete, in addition to trimming an input String. Useful for deleting unwanted line breaks. E.g. "\r\n\f" will delete all new lines and line feeds in a String.
I also use the latest version of JqGrid and Spring 3, but the way I handled the parameters seems to be simpler. Here's how I did it:
#Controller
#RequestMapping("/json")
public class JsonController {
#RequestMapping(method = RequestMethod.GET)
public #ResponseBody JsonResponse getAll(
#RequestParam("_search") String search,
#RequestParam(value="filters", required=false) String filters,
#RequestParam(value="datefrom", required=false) String datefrom,
#RequestParam(value="dateto", required=false) String dateto,
#RequestParam(value="page", required=false) String page,
#RequestParam(value="rows", required=false) String rows,
#RequestParam(value="sidx", required=false) String sidx,
#RequestParam(value="sord", required=false) String sord
) { ... }
All parameters are passed as normal Strings. The datefrom and dateto are custom parameters I passed from the JqGrid. The date comes from a JQuery's DatePicker and passed via JqGrid postData:
postData: {
datefrom: function() { return jq("#datepicker_from").datepicker("getDate"); },
dateto: function() { return jq("#datepicker_to").datepicker("getDate"); }
},
JsonResponse is a simple POJO that I used to map the search parameters passed by a JqGrid:
public class JsonResponse {
/**
* Current page of the query
*/
private String page;
/**
* Total pages for the query
*/
private String total;
/**
* Total number of records for the query
*/
private String records;
/**
* An array that contains the actual data
*/
private List<MyDTO> rows;
public JsonResponse() {
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getRecords() {
return records;
}
public void setRecords(String records) {
this.records = records;
}
public List<MyDTO> getRows() {
return rows;
}
public void setRows(List<MyDTO> rows) {
this.rows = rows;
}
}
MyDTO is a simple DTO object as well.
In my Spring applicationContext.xml, I just have to declare the following:
<mvc:annotation-driven/>
And added the Jackson jar for converting from JSON to POJO and vice versa
To convert the String date to a real Date, I used the great Joda library. But of course, you can use JDK's standard Date.
If you notice on my JSP, I added custom buttons. The onClickButton calls another Javascript function. For example on the Add button, I have the addRow function. Here's the function declaration:
function addRow() {
// Get the currently selected row
jq("#grid").jqGrid('editGridRow','new',
{ url: "/myapp/users/add",
editData: {
// Here you add extra post parameters
},
recreateForm: true,
beforeShowForm: function(form) {
// Here you can add, disable, hide elements from the popup form
},
closeAfterAdd: true,
reloadAfterSubmit:false,
afterSubmit : function(response, postdata)
{
// This is a callback function that will evaluate the response sent by your Controller
var result = eval('(' + response.responseText + ')');
var errors = "";
if (result.success == false) {
// Do whatever you like if not successful
} else {
// Do whatever you like if successful
}
// only used for adding new records
var new_id = null;
// Then this will be returned back to the popup form
return [result.success, errors, new_id];
}
});
}
Take note of the url:
url: "/myapp/users/add"
This is the mapping to your Controller that handles the add request
Now, for the Jackson serialization/deserialization, you'll be suprised how easy it is.
First, make sure you have the latest Jackson library in your classpath. Next, open your Spring xml config, and add the following:
<mvc:annotation-driven/>
That's it :)
Make sure you have the latest dependency jars. I use Spring 3.0.4. There's 3.0.5 already. Also, make sure you have the latest aspectjweaver.jar. If you wanna know what's inside that mvc-annotation-driven tag, just search the web and you'll see what it contains. Basically it automatically declares an HTTPMessageConverter for JSON, and uses Jackson by default.
For the Controller, here's the mapping to the /myapp/users/add request:
#Controller
#RequestMapping("/myapp/users")
public class UserController {
#RequestMapping(value = "/add", method = RequestMethod.POST)
public #ResponseBody JsonGenericResponse addAsJson(
#RequestParam("id") String id,
#RequestParam("firstName") String firstName,
#RequestParam("lastName") String lastName
) {
// Validate input
// Process data. Call a service, etc.
// Send back a response
// JsonGenericResponse is a custom POJO
// Jackson will automatically serialize/deserialize this POJO to a JSON
// The #ResponseBody annotation triggers this behavior
JsonGenericResponse response = new JsonGenericResponse();
response.setSuccess(false);
response.setMessage("Error in server");
return response;
}
}
Here's the JsonGenericResponse:
public class JsonGenericResponse {
private Boolean success;
private List<String> message;
public JsonGenericResponse() {
message = new ArrayList<String>();
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<String> getMessage() {
return message;
}
public void setMessage(String message) {
this.message.add(message);
}
}
It's just really a simple POJO.
In your JSP, to process the response, you use JavaScript in your JqGrid. The response will be sent back to whomever the caller (the add form in this case). Here's a sample JavaScript that will process the response:
if (result.success == false) {
for (var i = 0; i < result.message.length; i++) {
errors += result.message[i] + "<br/>";
}
} else {
jq("#dialog").text('Entry has been edited successfully');
jq("#dialog").dialog(
{ title: 'Success',
modal: true,
buttons: {"Ok": function() {
jq(this).dialog("close");}
}
});
}
return [result.success, errors, null];

Resources