I writing a simple Spring MVC web application that use JQuery DataTable on the client-side. DataTable using server-side processing mode. The DataTable make request with parameters(in my case):
draw:1
columns[0][data]:name
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:type
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:action
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
order[0][column]:0
order[0][dir]:asc
start:0
length:10
search[value]:
search[regex]:false
I don't know how can i parse parameters like columns[i][data], columns[i][name], columns[i][searchable], etc. The reason is why, because I don't know how many table columns I will have. How to solve this problem?
This is my Spring controller:
#RequestMapping(value = "/getImageWrappers", method = RequestMethod.POST)
public String getImageWrappers(#RequestParam Integer draw,
#RequestParam Integer start,
#RequestParam Integer length,
#RequestParam(value = "search[value]") String searchText){
}
and DataTable configuration:
$('#imageWrapperTable').DataTable({
columns:[
{"data" : "name"},
{"data" : "type"},
{"data" : "action"}
],
"processing": true,
serverSide: true,
ajax: {
url: '/getImageWrappers.json',
type: 'POST'
}
});
I just figure it out by adding this code
$('#imageWrapperTable').DataTable({
columns:[
{"data" : "name"},
{"data" : "type"},
{"data" : "action"}
],
"processing": true,
serverSide: true,
ajax: {
url: '/getImageWrappers.json',
type: 'POST',
datatype: 'json',
data: function(d){
//add your custom param here
d.name = "zxbing";
//this will put all query strings to a json object string
return JSON.stringify(d);
}
}
});
In this way, you just need to transfer only a query string to JSON object on the server side.
In a json array I would do something like this with jquery:
function displayData(x) {
x.success(function(data) {
$.each(data.columns, function(i, paramenter) {
$.each(parameter, function(a, b) {
$('#somediv').append('column'+parameter+' -> data: '+b+' ');
});
});
}),
x.error(function(data) {
//error message
})
}//end displayData
So you can loop through your array, but you gotta play around with it, I haven't tested it but in general that is the idea. Hope it helps.
Related
There is a Ajax call with JSON data of String, Array and Map. I am able to get String and Array data after converting into DashboardChartData (a Bean class) in jersey but not able to get Map values.
suppose bean is the object of DashboardChartData and globalInFilters is a data member of DashboardChartData Class and make setter/getter as same then
bean.getGlobalInFilters(); is getting null not desired value.
Code is:
function demo(){
var dashbord = {
"aoId": "M_AO_918",
"viewBys": ["Brand", "Category", "State"],
"viewIds": ["615228", "615128", "614847"],
"dimensions": ["615228"],
"aggregation": ["SUM", "SUM", "SUM", "SUM", "SUM", "SUM"],
"meassures": ["Gross Sales", "Net Sales", "Discount Amt", "Discount%", "Net Margin Amt", "Gross Margin Amt"],
"meassureIds": ["616275", "616283", "616279", "616648", "616295", "616303"],
"globalInFilters": {"615228": ["Lenovo", "Apple"]}
};
$("#query").html(JSON.stringify(dashbord));
$.ajax({
type: "POST",
contentType: "application/json; charSet=UTF-8",
dataType: "json",
data: JSON.stringify(dashbord),
url: "<%=request.getContextPath()%>/webresources/solrservice/test1",
success: function(data, textStatus, jqXHR){
alert('Bean created successfully');
},
error: function(jqXHR, textStatus, errorThrown){
alert('Bean error: ' + textStatus);
}
});
}
I have created DashboardChartData class with above parameter including:
private Map<String, List<String>> globalInFilters;
public Map<String, List<String>> getGlobalInFilters() {
return globalInFilters;
}
public void setGlobalInFilters(Map<String, List<String>> globalInFilters) {
this.globalInFilters = globalInFilters;
}
#Path("/test1")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void setData1(DashboardChartDataBean bean) throws Exception {
bean.getGlobalInFilters(); //getting null
ProgenSolrDao daoObj = new ProgenSolrDao();
try {
QueryResponse response = daoObj.executeSolrQuery("city",bean);
} catch (Exception e) {
}
}
bean.getGlobalInFilters() gets null, except this all other values is getting fine. please help how I can get the values of globalInFilters.
Why are you stringifying before sending it. Try without stringify.
I'm using jQuery jTable to list some data related to a class in my model. I send the request to the corresponding method responsable for fetching the data, and when I return the necessary JSON object I get an internal server error (500).
I don't get any exception or error code in my console, everything run as usual, except that I get this error and nothing else.
Here is the relevant part of the JSP:
$('#records').jtable({
messages : myMessages,
title: 'Records',
paging: true,
pageSize: 20,
sorting: true,
defaultSorting: 'date DESC',
actions: {
listAction: '/filter'
},
fields: {
id: {
title: 'Id',
list: true,
display:function(data){
return data.record.id;
}
},
date: {
title: 'Date',
list: true,
display:function(data){
return data.record.date;
}
},
userName: {
title: 'User',
list: true,
display:function(data){
return data.record.user.name;
}
},
dealerName: {
title: 'Dealer',
list: true,
display:function(data){
return data.record.dealer.name;
}
},
vendorName: {
title: 'Vendor',
list: true,
display:function(data){
return data.record.vendor.name;
}
},
totalValue: {
title: 'Total Value',
list: true,
display:function(data){
return data.record.totalValue;
}
},
recordStatus: {
title: 'Record Status',
list: true,
display:function(data){
return data.record.recordStatus;
}
},
paymentStatus: {
title: 'Payment Status',
list: true,
display:function(data){
return data.record.paymentStatus;
}
}
}
});
$('#records').jtable('load');
And here is the Spring MVC signature mapping the request:
#RequestMapping(value = "/filter", method = RequestMethod.POST)
public #ResponseBody JsonJTableResponse filter(int jtStartIndex,
int jtPageSize, String jtSorting, HttpServletRequest request) {
long st = Long.valueOf(jtStartIndex);
long sz = Long.valueOf(jtPageSize);
List<RecordTO> records = (List<RecordTO>) mgrRecord.getList();
JsonJTableResponse jtable = new JsonJTableResponse();
jtable.setResult("OK");
jtable.setTotalRecordCount(String.valueOf(mgrRecord.getListCount()));
jtable.setRecords(records);
return jtable;
}
The filter method is getting executed. The properties I set in jtable are being set. The only thing that maybe may cause some problem (even though I can't see why) is that the records list has RecordTO objects that don't have all their properties set, just the relevants for the jTable listing.
For example, the following properties are set:
(Long) id
(Date) date
(UserTO) user.name
(DealerTO) dealer.name
(UserTO) vendor.name
(Double) totalValue
(String) recordStatus
(String) paymentStatus
I have already looked in every corner for a solution but can't figure it out.
What could be the problem?
If you want more information that you may find it's relevant, just ask me.
Thanks.
I want to post a json string as plain string to a action ,then convert the string to List using gson, but the string is still treated as json object by jquery/webwork, I'm using jquery 1.43+webwork+gson, no jquery json plugin or something.
here is action:
public class ImageAction extends BaseAction {
private String pks;
public void setPks(String pks) {
this.pks = pks;
Gson gson=new Gson();
List<Map> list=gson.fromJson(pks,new TypeToken<List<Map<String,String>>>(){}.getType());
System.out.println(list.size());
}
......
}
jquery code:
j$.ajax({
url:approveUrl,
data: {pks:'[{"userName":"theoffspring"}]'},
// dataType:'json',
type:'post',
// traditional: true,
success:function (response) {
hideProgressBar(parent.document)
if (response.result==false){
alert(response.msg);
return;
}
// document.location.reload();
}
})
I want pks posted as a common string instead of json object. But setPks method turns out not to be invoked when I invoke the jquery code. So strange.
you have'nt serialized the data you are sending through ajax.serialize it at client using JSON.stringify() and send it will be converted to a single string.
modify your code to:
$.ajax({
url:approveUrl,
data:JSON.stringify(yourdata),
// dataType:'json',
type:'post',
// traditional: true,
success:function (response) {
hideProgressBar(parent.document)
if (response.result==false){
alert(response.msg);
return;
}
// document.location.reload();
}
})
this might work.
Have a look at this: http://jsfiddle.net/flocsy/vuGL9/
You'll see that your pks is actually sent as a string as you want it, when it's not sent as a string (pks2) it'll look different.
PS: look at the network tab in firebug or inspect element, depending on your browser:
pks: '[{"userName":"theoffspring"}]'
pks2[0][userName2]:'hehe'
So probably your server side does some magick...
I am trying to pass a user defined parameter to the Java Controller which acts as a data source to my jquery Data-Table.
The point is, i want to do this (pass the parameter) on a change event for a combobox on my jsp.
Here is my datatable initialization:
var oTable = $('#reqAllQueriesTable')
.dataTable(
{
"sDom": '<"H"l<"projectTeamTools">frtip>',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "query/getQuery",
"bPaginate" : true,
"bLengthChange": true,
"bScrollCollapse" : true,
"iDisplayLength" : 10,
"bFilter" : true,
"bJQueryUI" : true,
"sPaginationType" : "full_numbers",
"sSearch": "Search"
});
My combobox whose values are to be passed to the controller and the respective functions are:
$("div.projectTeamTools").html('Organize by Project Teams: <select id="projectTeams"><option value="0">Project Team</option><option value="1">All</option><option value="2">Not Associated</option><c:forEach var="projectTeam" items="${userProjectTeams}"><option value="${projectTeam.projectId}">${projectTeam.projectName}</option></c:forEach></select>');
$("#projectTeams").change(function () {
onTeamSelect($(this).val());
});
function onTeamSelect(teamId){
alert(teamId +" Selected");
//This function to pass the parameter to the datatable is supposed to be here.
oTable.fnDraw();
}
The datatable then displays the new data it receives from the ajax Source getQuery.
PS: I cannot use fnServerParams as I am using the older version of datatables. I have tried using fnServerData but it did not help. I guess I am wrong in the way I am using the ajax function in fnServerData.
"fnServerData": function ( sSource, aoData, fnCallback ) {
$("#projectTeams").change(function() {
aoData.push( { "name": "myParam", "value": $("#ComboBox option:selected").value() } );
$.ajax( {
"dataType": 'json',
"url": sSource,
"data": aoData,
"success": fnCallback
});
I cannot see the parameter I want to pass in the 'Network XHR' in my browser when I select an item from the combo-box.
Please help!
Got an answer. During initialization, fnServerData should be:
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( { "name" : "myTeamId", "value" : myTeamId } );
$.getJSON( sSource, aoData, function (json) {
fnCallback(json);
});
}
and the onChange function of the combobox on which I want to pass the parameter:
$("#projectTeams").change(function () {
onTeamSelect($(this).val());
});
function onTeamSelect(teamId){
myTeamId = teamId;
oTable.fnDraw();
}
where myTeamId is a global variable.
The oTable.fnDraw() redraws the datatable and assigns the value of teamId to the myTeamId, which I use in fnServerData.
This code worked for me!
I have a web application with HTML / jQuery which ic connected with AJAX / JSON to a backend system with Java EE / Spring MVC.
In the frontend, a Person can be created by fill in the form fields and then it is submitted and this jQuery code executed:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
});
In the best case, the Person is created and I'll get a Person object and I can access the values with data.person.*.
Now I want to validate the data which is sent to the backend system and in a case of an error, I want to display in the first step an alert error message.
I did this in the backend system:
#RequestMapping(value="add/", method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> addPerson(#RequestBody Person p, HttpServletResponse response) {
Set<ConstraintViolation<Person>> failures = validator.validate(p);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
Person person = this.personService.addPerson(p);
return Collections.singletonMap("person", new SerialPerson(person.getId(), person.getName(), ...));
}
}
// internal helpers
private Map<String, String> validationMessages(Set<ConstraintViolation<Person>> failures) {
Map<String, String> failureMessages = new HashMap<String, String>();
for (ConstraintViolation<Person> failure : failures) {
failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage());
System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage());
}
return failureMessages;
}
My Person object is annotated, and I get the System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage()); on the console, that for example, "name - must be between 1-30 chars"
But how can create an alert message in jQuery in the frontend system?
Thank you in advance for your help & Best Regards.
Update: Link to the Spring MVC AJAX example, where I found the validationMessages method. But there is also no solution how to get the error message.
SOLUTION:
I have to call:
jQuery.ajax({
'type': 'POST',
'url': "add/",
'contentType': 'application/json',
'data': JSON.stringify(person),
'dataType': 'json',
'success': function(data) {alert("success");},
'error': function(xhr) {alert(xhr.responseText);}
});
You can do something like this:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
if(data.person) {
alert("Person with ID "+data.person.id+"' added successfully");
}
else {
var errors = "";
for(var key in data) if(data.hasOwnProperty(key)) {
errors += data[key] + "\n";
}
alert(errors);
}
});
You shouldn't need to send back a bad request either. Is this what you want?
UPDATE
You can use the code shown in Spring Source, but you'd have to use jQuery.ajax
jQuery.ajax({
type: 'POST',
url: "add/",
data: person,
dataType: "json",
success: function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var errorJSON = JSON.parse(XMLHttpRequest.responseText); //if this is JSON otherwise just alerting XMLHttpRequest.responseText will do
var errors = "";
for(var key in errorJSON) if(errorJSON.hasOwnProperty(key)) {
errors += errorJSON[key] + "\n";
}
alert(errors);
}
});