Reputation: 327
Can anyone tell me how to set the response to jquery data to each table columns.
Here is my javascript code:
$(document).ready (function() {
$.ajax({
url: 'userController?action=list',
success : function(response) {
var jsonObject = $.parseJSON(response);
alert(jsonObject.Password);
alert(jsonObject.UserId);
$('#usertable').dataTable( {
data : jsonObject,
columns: [
{'jsonObject' : 'UserId'},
{'jsonObject' : 'Password'},
{'jsonObject' : 'Level'},
],
searching : false
});
}
});});
Here the response in String and the response is
{"UserId" : "Manohar", "Password" : "1234", "Level" : "lev"}
.
Below is the jsp page.
<table id="usertable">
<thead>
<tr>
<th>User Id</th>
<th>Password</th>
<th>Level</th>
</tr>
</thead>
I have written the above and neither I am getting error nor the row is added to table. Can you guys help me in this?
Upvotes: 6
Views: 29017
Reputation: 327
Here the solution is to change the response. Earlier it was {"userid":"manohar", "password":"1234"}, now I have changed it to [["manohar", "1234"]]. Then in js file
$.ajax({
url: 'userController?action=list',
success : function(data, textStatus, jqXHR) {
var table_data = JSON.parse(data);
var table = $('#usermaintenancetable').DataTable( {
data: table_data
}); } });
So here the response is in String format and I have change it to JSON using JSON.parse() then passed this as data to data table.
Upvotes: 3
Reputation: 17345
You shouldn't reinitialize the datatable inside your success method. Once you have the json object response, you should use row.add() method,
Sol 1: (For looping JSON objects)
success:function(data, textStatus, jqXHR) {
$.each(data, function (i,item) {
var rowNode= [ item.UserId, item.Password, item.Level]
dataTable.row.add(rowNode).draw();
});
}
Sol 2 :(For JSON string values)
success:function(data, textStatus, jqXHR) {
var jsonData = JSON.parse(data);
var rowNode= [ jsonData.UserId, jsonData.Password, jsonData.Level]
dataTable.row.add(rowNode).draw();
}
The above code adds one row at a time. For adding multiple rows at once, use rows.add() API method
Upvotes: 2
Reputation: 585
use this
$(document).ready (function() {
$.ajax({
url: 'userController?action=list',
success : function(response) {
var jsonObject = $.parseJSON(response);
alert(jsonObject.Password);
alert(jsonObject.UserId);
$('#usertable').dataTable( {
data : jsonObject,
//data : response,
columns: [
{"data" : "UserId"},
{"data" : "Password"},
{"data" : "Level"}
],
searching : false
});
}
});});
change only jsonObject
to data
Try Another Method u can use ASP.NET MVC
$(document).ready(function () {
$.get("/userController/list", function (data) {
// console.log(data);
if (data != null) {
$('#usertable').dataTable({
data: data,
columns: [
{"data" : "UserId"},
{"data" : "Password"},
{"data" : "Level"}
],
searching : false
});
}
})
});
Upvotes: 0