DataTables error loading ajax source data - c#

I am getting the following error when trying to load DataTables ajax sourced data:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Below is my DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Below is my DataTables javascript:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Below is the confirmed json my C# controller is returning for the DataTables ajax data:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
The error seems to be related to the JSON format, but not sure what is wrong?
EDIT:
Adding full javascript code:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>

Your <script> block should look like this to initialize your data for your Data Tables:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
method: "post",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data":data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>

the data source should be an array of arrays that contains the data in the tbody
say
data = [
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"],
["foo","foo","foo","foo","foo"]
];
see the example [https://datatables.net/examples/data_sources/js_array.html][1]
additionally, use data: data.data instead of "ajax" : data

As your JSON response is an object but not an array, specify the ajax to get the JsonResponse.data as below:
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": function (json) {
return json.data;
},
},
OR
"ajax": {
"url": /* Your Get Data API url */,
"dataSrc": "data"
},
JQuery answer
Updated: Change from json.data to data as Post Owner changed requirement.
data: data
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"data": data,
... // Remaining DataTable configurations
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
Output
Reference
ajax - DataTables.net

Related

Json data is not showing in datatable using ASP.NET

I am using ASP.NET; I am getting the data from the backend as expected, but it is not showing in the web page using a datatable.
Web page:
#{
ViewBag.Title = "Employee";
}
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
JavaScript portion of code (jQuery)
$(document).ready(function () {
$('#myTable').DataTable({
processing:true,
"ajax": {
"url": "/Employee/GetList",
"type": "GET",
"dataType": "json",
"success": function (msg) {
console.log(msg.data);
},
"failure": function (response) {
alert(response);
},
"error": function (response) {
alert(response);
}
},
"columns": [
{ data: "EmployeeId" },
{ data: "Name" },
{ data: "Age" },
{ data: "Position"},
]
});
});
Here is the response I am getting from the backend. This is the data I copied from Netword -> Response tab against the endpoint I call to fetch the data
{
"data": [
{
"EmployeeId": 1,
"Name": "Dhruv",
"Age": 23,
"Position": "Full Stack Developer"
},
{
"EmployeeId": 2,
"Name": "Soni",
"Age": 21,
"Position": "DBA"
},
{
"EmployeeId": 3,
"Name": "Mike",
"Age": 24,
"Position": "Frontend Developer"
},
{
"EmployeeId": 4,
"Name": "Bob",
"Age": 20,
"Position":"SRE"
}
]
}
I am trying to get the data from database and show it to the user using a datatable. I am successfully getting the response back from the database, but the data is not showing inside the table. And I can't figure it out why....
Update:3
Controller:
public ActionResult GetList()
{
var empList = new List<Employee>()
{
new Employee(){ EmployeeId = 1, Name = "A", Age = 19, Position = "Engineer-I"},
new Employee(){ EmployeeId = 2, Name = "B", Age = 20, Position = "Engineer-II"},
new Employee(){ EmployeeId = 3, Name = "C", Age = 21, Position = "Engineer-I"},
new Employee(){ EmployeeId = 4, Name = "D", Age = 22, Position = "Engineer-III"},
};
return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
}
Note: You even can directly return Json(new { empList }) in that case, in your HTML-Ajax you only have to write return msg; not msg.data
View:
<h2>Employee List</h2>
<table id="myTable">
<thead>
<tr>
<th>EmployeeId</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/DatatableInAnotherWay/GetList",
"dataSrc": function (msg) {
console.log(msg.data);
return msg.data;
}
},
"columns": [
{ "data": "employeeId" },
{ "data": "name" },
{ "data": "age" },
{ "data": "position" },
]
});
});
</script>
}
Note: I am returning as return Json(new { data = empList }); so I would receive response as msg.data. Check the response in your browser console as below:
Importantly, be sure about the column case as you can see I am getting it as lower-case so I bind them as like this"data": "employeeId". As you are saying you are getting in Upper-Case as EmployeeId you should then bind as "data": "EmployeeId"
Final Output:
Special Note:
Remember these words forver, If you want to be a great programmer, you must concentrate on :
Debugging
Code readability
Self reading/teaching attitude
Update:2
If you still want to persist with your code: You could do as following:
$('#myTable').DataTable({
processing: true,
"ajax": {
"type": "GET",
"url": "/Employee/GetList",
"dataSrc": function (msg) {
return msg;
}
},
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
});
Issue on your code:
You were defining the column in worng way: you should do it in following way:
"columns": [
{ "data": "EmployeeId" },
{ "data": "Name" },
{ "data": "Age" },
{ "data": "Position" },
]
Update:2 Output:
Update:
Based on your updated question, its clearly seen that you are ajax calling pattern is incorrect. How your msg.data would be bounded into your "columns": no way. Please try my updated code. Just copy and paste.
I am successfully getting the response back from the database but the
data are not showing inside the table. And i can't figure it out why?
It's because of your row definition in your columns within the datatable.
You would define all of your data members in lower case - like
"columns": [
{ data: "employeeId" },
{ data: "name" },
{ data: "age" },
{ data: "position"},
]
Note: UpperCase EmployeeId, Name etc in jQuery datatable are causing parsing issues. In addition, please follow the $.ajax({}); calling format as per my demo for better code readability.
Complete example:
<table id="myTable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Position</th>
</tr>
</thead>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Employee/GetList",
success: function (response) {
$('#myTable').DataTable({
data: response,
columns: [
{ data: 'EmployeeId' },
{ data: 'Name' },
{ data: 'Age' },
{ data: 'Position' }
]
});
},
error: function (response) {
alert(response.responseText);
}
});
});
</script>
}
Output:

Call Post action method from jquery ajax request

How can I call action method from jquery ajax form? I create below code, but parameters in my action method is always null.
Note: I already added all needed scripts, such as quill.js, jquery.unobtrusive-ajax.js
I have this form:
<form data-ajax="true" data-ajax-method="post" method="post">
<input type="text" name="postTitle" class="form-group" />
<div id="postData" name="postData"></div>
<br />
<button type="submit" class="btn btn btn-outline-dark" id="btnCreate">Create post</button>
</form>
and this javascript and jquery scripts:
QUILL:
<script>
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['link', 'image', 'video', 'formula'], // add's image support
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
];
var quill = new Quill('#postData', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
</script>
Calling post action method:
$(function () {
$('#btnCreate').click(function () {
var props = [{
"PostTitle": $("postTitle"),
"PostData": quill.root.innerHTML
}]
$.ajax({
url: '#Url.Action("Create", "Post")',
type: "POST",
data: { JSON.stringify(props) },
contentType: "application/json",
dataType: "json",
async: true,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc(e) {
console.log('Error!', e);
}
//console.log(postData);
});
});
My action method:
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string props) // here props is null
{
Post post = new Post { PostBody = props };
db.Posts.Add(post);
await db.SaveChangesAsync();
return View();
}
I think that every input element is obtained from val ();
$("postTitle").val() maybe

Data received in controller from ajax is NULL?

I am receiving null in both ProductData and ProductDetailsData when data is sent from ajax to controller. What could be the issue ?
IN CONTROLLER :
public bool UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
return Json(DrugService.UpdateProduct(ProductData, ProductDetailsData));
}
IN JS FILE :
$(document).on("click", "#btn_update", function () {
//Prepare data
var ProductDataArray = [];
var ProductDetailsDataArray = [];
ProductDataArray.push({
"Name": $('#txt_drugname').val(),
"CommercialName": $('#txt_drugcommercialname').val(),
"PackageType": $("#dd_packagetype option:selected").val(),
"DrugType": $("#dd_drugtype option:selected").val(),
"DrugCode": $('#txt_drugcode').val(),
"ProductId": $('#hdn_productid').val(),
"Administration": $('#txt_administration').val(),
"Manufacturer": $('#txt_manufacturer').val(),
"Price": $('#txt_price').val(),
"Strength": $('#txt_stregnth').val(),
"StregnthUnit": $("#dd_stregnthunit option:selected").val(),
"Barcode": $('#txt_barcode').val(),
"IsEnabled": $("#dd_isenabled option:selected").val(),
"UpdatedOn": new Date(),
"UpdatedBy": 'UserNme',
});
ProductDetailsDataArray.push({
"ProductId": $('#hdn_productid').val(),
"ProductDetailsId": $('#hdn_productdetailid').val(),
"Length": $('#txt_Legnth').val(),
"Width": $('#txt_width').val(),
"Height": $('#txt_height').val(),
"ConversionRate": $('#txt_conversion').val(),
"DrugForm": $("#dd_drugform option:selected").val(),
"StoredAs": $("#dd_storedas option:selected").val()
});
//Send data
$.ajax({
url: '/Drug/UpdateProduct/',
type: 'POST',
data: { 'ProductData': ProductDataArray, 'ProductDetailsData': ProductDetailsDataArray },
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
}
});
});
You have several issues in both AJAX and controller action method:
1) You're tried to pass arrays into data using contentType set to application/json without doing JSON.stringify() first, therefore it won't work since array required to pass either as JSON string or use traditional: true setting.
2) The action method parameter types are not set to array but a single entity class like viewmodel, you need to declare an object instead of array.
3) The controller action uses bool return type which should use JsonResult (or ActionResult) type.
Based from those mistakes mentioned above, try to use setup like below:
jQuery
$(document).on("click", "#btn_update", function () {
var ProductDataArray = {
"Name": $('#txt_drugname').val(),
"CommercialName": $('#txt_drugcommercialname').val(),
"PackageType": $("#dd_packagetype option:selected").val(),
"DrugType": $("#dd_drugtype option:selected").val(),
"DrugCode": $('#txt_drugcode').val(),
"ProductId": $('#hdn_productid').val(),
"Administration": $('#txt_administration').val(),
"Manufacturer": $('#txt_manufacturer').val(),
"Price": $('#txt_price').val(),
"Strength": $('#txt_stregnth').val(),
"StregnthUnit": $("#dd_stregnthunit option:selected").val(),
"Barcode": $('#txt_barcode').val(),
"IsEnabled": $("#dd_isenabled option:selected").val(),
"UpdatedOn": new Date(),
"UpdatedBy": 'UserNme',
};
var ProductDetailsDataArray = {
"ProductId": $('#hdn_productid').val(),
"ProductDetailsId": $('#hdn_productdetailid').val(),
"Length": $('#txt_Legnth').val(),
"Width": $('#txt_width').val(),
"Height": $('#txt_height').val(),
"ConversionRate": $('#txt_conversion').val(),
"DrugForm": $("#dd_drugform option:selected").val(),
"StoredAs": $("#dd_storedas option:selected").val()
};
$.ajax({
url: '/Drug/UpdateProduct/',
type: 'POST',
data: JSON.stringify({ 'ProductData': ProductDataArray, 'ProductDetailsData': ProductDetailsDataArray }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
// do something
}
});
});
Controller Action
[HttpPost]
public ActionResult UpdateProduct(Entity_Product ProductData, Entity_ProductDetails ProductDetailsData)
{
return Json(DrugService.UpdateProduct(ProductData, ProductDetailsData));
}

Ensuring that jquery DataTable can sort based on invoking by AJAX a Server-Side C# method

Here is the information about my development environment:
Microsoft Visual Studio Professional 2013
.NET Framework 4.0
jquery.min.js 1.11.3
jquery-ui.min.js 1.11.2
jQuery DataTables 1.10.7
Newtonsoft.Json.7.0.1
We implemented the tables on our website using jQuery DataTables that involved Server-Side Pagination. In other words, the application will only retrieve data from the database as the user clicks on the Page numbers or Page arrow keys at the bottom of the table.
$('#GameMatchRecordsLogTable').DataTable({
"aoColumns": [
{ "sTitle": "MatchId" },
{ "sTitle": "OrganizerUserID" }, {
"sTitle": "Team1", "bSortable":
true }, { "sTitle": "Team2",
"bSortable": true },
{ "sTitle": "DATE", "sType":
"datetime-us-asc", "bSortable":
true },
],
"bAutoWidth":false,
"fnRowCallback": function (nRow, aData,
iDisplayIndex) {
$(nRow).addClass("gradeX");
},
"iDisplayLength": 10,
"sDom": '<"clear">frtip',
"bProcessing": true,
"bServerSide": true,
"bLengthChange": false,
"bPaginate": true,
"bDestroy": true,
"bSort": true,
"aaSorting": [],
"bInfo": true,
"bFilter": false,
"sAjaxSource":
'GameMatchesList.aspx/SearchBasedOnMultipleCriteriaForGameMatches',
"bJQueryUI": true,
"bDeferRender": true,
"fnServerParams": function (aoData) {
aoData.push(
{ "name": "sortColumnArg",
"value": sortColumnArg }
, { "name": "isDescendingArg",
"value": isDescendingArg }
, { "name": "startDateArg",
"value": startDateArg }
, { "name": "endDateArg", "value":
endDateArg }
, { "name": "OwnersNameArg",
"value": OwnersNameArg }
, { "name":
"searchDrpDutyCycleArg", "value":
searchDrpDutyCycleArg }
, { "name":
"searchDrpSignedStateArg", "value":
searchDrpSignedStateArg }
);
},
"fnServerData": function (sSource, aoData,
fnCallback) {
$.ajax({
"dataType": 'json',
"contentType": "application/json;
charset=utf-8",
"type": "GET",
"url": sSource,
"data": aoData,
"success":
function (msg) {
var obj =
jQuery.parseJSON(msg.d);
fnCallback(obj);
},
beforeSend: function () {
$('.loader').show()
},
complete: function () {
$('.loader').hide()
}
});
}
});
The back-end C# code will resemble something like the following:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.Bare, Method = "GET")]
public static string
SearchBasedOnMultipleCriteriaForGameMatches()
{
return null;
}
We also need Server-side based sorting for the title headers of the jquery DataTable.
To elaborate, we want user to be able to click on the title Header of the DATE column which would in turn invoke AJAX method which in turn invokes a Server-side C# to get all the Data based on a particular order of the Date , therefore, if user toggles then it would go back and forth between descending and ascending of Date ).
Could someone please explain how I could implementing the aforementioned requirement?

Issue with JSON data from .NET to jqGrid

I have a dynamic function to generate table data to JSON which kinda works, now I try to add it to a list in .NET however I can't get this right past few days, anybody knows what I do wrong?
the output is like this:
[{"itemsSerialized":"{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"},{"itemsSerialized":"{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"}]
which should be without the "itemsSerialized":", I understand where it comes from, but dont understand why a object declaration suddenly shows up in my JSON string
my C# code:
Object itemsSerialized = "";
foreach (DataRow r in _data.Rows)
{
DynamicClass dynamicClass = new DynamicClass();
dyna.ConvertRowToCustomer(r, out dynamicClass);
DynamicClassList.Add(dynamicClass);
var iSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Object itemsSerialized2 = JsonConvert.DeserializeObject(xJSON);
Gridist.Add(new { itemsSerialized });
}
with jQuery I have this to load the data into the jQGrid:
$.ajax({
type: "POST",
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
data: "{ 'q': 'med&1'}",
dataType: 'json',
success: function (result) {
var str = result.d;
alert(result.d);
$("#jqGrid_2")[0].addJSONData(result.d);
}
});
The return I have now as:
{"id":1,"name":"Medical 1","city":"Kiev","instituteTypeId":0},{"id":2,"name":"Medical 2","city":"Kherson","instituteTypeId":0}
UPDATE INTERNAL AJAX VERSION:
mtype: 'POST',
contentType: "application/json",
url: "dataServices/objects.asmx/InvokeData",
ajaxGridOptions: {
contentType: 'application/json; charset=utf-8'
},
postData: JSON.stringify({q: "med&1"}),
loadonce: true,
dataType: 'json',
jsonReader: {
root: function (obj) {
alert(obj.d);
return obj.d;
},
page: "",
total: "",
records: function (obj) {
return obj.d.length;
},
},
gridview: true,
loadError: function (xhr, status, error) {
alert('load error: ' + error);
},
And is being written away in the first column from first and only row....
What I do wrong and how I get the itemsSerialized out
First of all the server response
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
is wrong. Correct data should be array of items like
[
{
"id": 1,
"name": "Medical 1",
"city": "Kiev",
"instituteTypeId": 0
},
{
"id": 2,
"name": "Medical 2",
"city": "Kherson",
"instituteTypeId": 0
}
]
Another JSON response which you posted contains two problems. 1) "itemsSerialized":" prefix 2) the value of all items are strings
[
{
"itemsSerialized": "{\"id\":1,\"name\":\"Medical 1\",\"city\":\"Kiev\",\"instituteTypeId\":0}"
},
{
"itemsSerialized": "{\"id\":2,\"name\":\"Medical 2\",\"city\":\"Kherson\",\"instituteTypeId\":0}"
}
]
The reason of the first problem is the usage of
Gridist.Add(new { itemsSerialized });
instead of
Gridist.Add(itemsSerialized);
The reason of the second problem is unneeded usage of JsonConvert.SerializeObject. What you should do is something like
Gridist.Add(dynamicClass.Property.properties);
instead of
itemsSerialized = JsonConvert.SerializeObject(dynamicClass.Property.properties);
Gridist.Add(new { itemsSerialized });

Categories

Resources