Jquery Datatables Error: Invalid JSON primitive: draw - javascript

I am trying to implement server side processing with JQuery Datatables 1.10.5. Here is my code for the DataTable
$('#userTable').dataTable({
serverSide: true,
ajax: {
type: "POST",
data: {
'statusFilter': $('#status-filter').val(),
'secondaryFilterOption': $('#secondary-filter-option').val(),
'secondaryFilterOperator': $('#secondary-filter-operator').val(),
'secondaryFilterText': $('#secondary-filter-text').val()
},
url: "UserManagement.aspx/GetUsers",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (jqXhr, textStatus, errorThrown) {
alert(jqXhr.responseText);
}
},
scrollY: "500px",
scrollCollapse: true,
columnDefs: [
{
"targets": [0],
"visible": false,
"searchable": false
},
{
"targets": [8],
"visible": true,
"searchable": false,
"render": function (data, type, row, meta) {
return '<img title="Edit" class="action-button edit-user center" src="/ntims/images/icon_edit.gif" id="' + row.id + '" />';
},
}],
columns: [
{ "data": "id" },
{ "data": "lastName" },
{ "data": "firstName" },
{ "data": "login" },
{ "data": "command" },
{ "data": "email" },
{ "data": "phone" },
{ "data": "status" }
]
});
I get the following error during the ajax call:
{"Message":"Invalid JSON primitive: draw.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
"draw" is something that datatables sends to the server. I have no control over this variable to my knowleged. I have looked at the Jquery Forums and did some other research but I cannot firgure out this issue. I have seen people have issues about other parameters that THEY are sending, but "draw" is something Jquery sends, not me.

You can give "bServerSide" : true for serverSide: true.
If it doesnt work check with "serverSide": true

Related

how to add a href route with parameter in datatable

here is i have a datatable based table i have fetched a data from database and displayed using datatable but in this datatable i went to redirect to show for each row of datatable so how to add a route for show with parameter 1d for each row thanks and waiting a positive response!
here is my code
<script>
$(function() {
$("#start_date").datepicker({
"dateFormat": "yy-mm-dd"
});
$("#end_date").datepicker({
"dateFormat": "yy-mm-dd"
});
});
// Fetch records
function fetch(start_date, end_date,zone_id,status_id,sector_id) {
$.ajax({
url: "{{ route('ProjectFilterdate/records') }}",
type: "GEt",
data: {
start_date: start_date,
end_date: end_date,
zone_id:zone_id,
status_id:status_id,
sector_id:sector_id
},
dataType: "json",
success: function(data) {
// Datatables
var i = 1;
$('#records').DataTable({
"data": data.ptojects,
// buttons
"dom": "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
"buttons": [
'copy','excel', 'pdf', 'print'
],
// responsive
"responsive": true,
"columns": [{
"data": "id",
"render": function(data, type, row, meta) {
return i++;
}
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "proposal_date"
},
{
"data": "proposal_value"
},
{
"data": "contractor"
},
{
"data": "subcontractor"
},
{
render: function ( data, type, row) {
return 'test';
}
},
]
});
}
});
}
i am trying to make an a href route but i don't know how to add an id parameter
here is the link i am trying
{
render: function ( data, type, row) {
return 'test';
}
the place of 1 must be replaced by id for each row
This is how i did t :
return DataTables::of($data)->addIndexColumn()
->addColumn('project', function ($test) {
return $test->project->title;
})
->addColumn('action', function ($test) {
$result = $test->active ? 'btn-success' : 'btn-danger';
return '<a href="' . route('projectDetail', [
'id' => $test->id
]) . '">detail </a>
';
})
->rawColumns([
'action'
])
->make(true);
}

How to get all ID's of all Checked data in all pages on Datatables

Hi i have my datatables with checkbox at the first column
i able to get the checked checkbox id but i cannot get all the data on the other page
i have this to render my datatables
var tableDelcar;
function LoadTableDelcar() {
tableDelcar = $('#tblDelcar').DataTable({
//dom: 'Brtip',
order: [[1, 'asc']],
buttons: [
'csv', 'excel', 'pdf', 'print'
],
pageLength: 10,
"ajax": {
async: false,
type: 'POST',
contentType: 'application/json',
url: 'MaintenancePage.aspx/getCarDelMaintable',
"dataSrc": "d",
dataType: 'json',
},
"columns": [
{
"d": null,
render: function (data, type, row, meta) {
return '<input type="checkbox" class="select" id="' + row.CAR_NO + '"></td>';
}, title: "Action"
},
{ "data": "CAR_NO", title: "Car No" },
{ "data": "FINDINGS", title: "FINDINGS" },
{ "data": "ActionOwner", title: "Action Owner" },
{ "data": "Auditor", title: "Status" },
{ "data": "COORDINATOR", title: "COORDINATOR" }
]
});
}
and this is my function on getting the ID's of the checked checkboxes
function DeleteCar() {
var IDs = $("#tblDelcar input:checkbox:checked").map(function () {
return $(this).attr("id");
}).get(); alert(IDs);
}
Make sure your DOM is loaded when you call your function in the other page.
you have error ?

API in javascript is returning data, but is not being saved into an array

I am trying to fetch data from an API of WordPress.
Here is my code:
column.data().unique().sort().each(function (d,j) {
var practiceArea = d.practice_area;
var jsonPacticeArea = JSON.stringify(practiceArea);
if (jsonPacticeArea !== undefined) {
var res = $.map(jsonPacticeArea.split("|"), $.trim);
for (var i = 0; i < res.length; i++) {
var str = res[i];
str = str.replace(/"/gi, '').trim();
if (arrayPracticeArea.indexOf(str) === -1) {
arrayPracticeArea.push(str);
}
}
}
});
the "column" is the variable that is getting data through an API, and as far as I do console.log(column. data().unique().sort()), that's returning complete data as you can see in the screenshot and I want to fetch data is marked in red rectangle and store those values in an array, but as soon as I try to add "each" function to fetch the data and store it in an array (in my case its arrayPracticeArea) its returning undefined values.
Can anyone please help me out? I am just not much experienced with Javascript API.
Here is my AJAX code:
var tableAttorney = $('#table_affliate_attorney').DataTable({
destroy: true,
searching: true,
bLengthChange: false,
scrollX: true,
scrollY: 440,
autoWidth: false,
"language": {
"emptyTable": "We are sorry but there are no Affiliate Attorneys within a 150 mile radius of your requested search"
},
ajax: {
type: 'get',
url: "/wp-admin/admin-ajax.php",
dataType: 'json',
cache: false,
data: {
'action': 'get_attorney_ajax',
'center_lat': center_lat,
'center_long': center_long,
'state': state,
'city': city,
'zip': zip
}
},
columns: [
{"data": "title"},
{"data": "city"},
{"data": "state"},
{"data": "zip"},
{"data": "distance"},
{
"data": "phone",
className: 'datatablePhone',
render: function (data) {
return '' + data + '';
}
},
{
"data": "email",
className: 'px190EM',
render: function (data) {
return '' + data + '';
}
},
{
className: 'js-practice-area',
"data": "practice_area"
},
{
"targets": -1,
"data": 'email',
render: function (data) {
return "<a class='contact-lawyer' href='#' data-toggle='modal' data-target='#exampleModal' data-whatever='#mdo' data-email='"+data+"'>Contact</a>";
}
},
],
columnDefs: [
{"width": "150px", "targets": [0]},
{"width": "130px", "targets": [5]}
],
So I am trying to fetch data from columns->data that has value practice_area

Passing row data from DataTables to method in controller with parameter row data

I have a link in my datatable that will call a method in my controller and pass the row data as my parameter. but the value showing is [Object] [object] how should i pass it on my controller method as a list or dictionary?
I already tried to stringtify but it has an error showing that the query string is too long.
$.ajax({
url: urlGetRequest,
cache: false,
type: "POST",
success: function (resultdata) {
data = resultdata.aaData;
if ($.fn.DataTable.isDataTable('#tblSolutioning')) {
$('#tblSolutioning').DataTable().destroy();
}
$("#tblSolutioning").DataTable({
"bProcessing": true,
"aaData": data,
"columns": [
{
"mData": "RequestID",
"bSearchable": true,
"bSortable": true,
"mRender": function (data, type, row, meta) {
//return '' + data + '';
return "<a href='ManageSolution?rowRequest= " + rowData + " ' onclick='setBackUrl(window.location.href)'>" + data + "</a>";
}
},
],
"columnDefs": [{
"targets": '_all',
"searchable": true
}]
});
}
});
public ActionResult ManageSolution(Dictionary<string,string> rowRequest)
{
}

How to show data from get request in datatable?

I have been trying to show a json response of my rest application which is a rest application using tomcat server and i am using angular in the frontend and here is my controller
(function(){
'use strict';
angular.module('app')
.controller('wfCtrl', wfCtrl);
function wfCtrl($scope, $location, $http) {
var table=$('#example1').DataTable(
{
"bServerSide": true,
"fnServerData": function (sSource, aoData, fnCallback) {
var myData = JSON.stringify(aoData);
$.ajax({
"dataType": 'json',
"contentType" : "application/json;charset=utf-8",
"type": "GET",
"url": "http://localhost:8080/Spring4/data/lworkflows",
"data": null,
"success": fnCallback,
"error": function () {
console.log('have some problem');
}
});
},
"aoColumns": [
{ "mData": null }, // for User Detail
{ "mData": "code" },
{ "mData": "label" },
{ "mData": null },
{ "mData": null },
{ "mData": null },
{ "mData": null },
]
,
"order": [[ 1, "desc" ]]});
})();
the request url "http://localhost:8080/Spring4/data/lworkflows" returns a json data like this
{"WFLIGHT":{"code":"WFLIGHT","label":"Submit the deal"},"WFCOM":{"code":"WFCOM","label":"COM"},"WFPOCTBR":{"code":"WFPOCTBR","label":"Workflow Retail POC VW"},"WFRISK":{"code":"WFRISK","label":"RISQUES"},"WFDECF":{"code":"WFDECF","label":"DECIDEUR"},"WFETUDE":{"code":"WFETUDE","label":"ETUDE"},"WFADV":{"code":"WFADV","label":"ADV"},"TEST1":{"code":"TEST1","label":"Workflow Retail POC VW"},"WFCOM2":{"code":"WFCOM2","label":"ASSCOM"}}
the error i am getting is
Uncaught TypeError: Cannot read property 'length' of undefined
since my datatable cant read the data sent from the request
How can i resolve that ?
resolved after converting the response to an arrays
var output = wfs.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
here's the full working code
function wfCtrl($scope, $location, $http) {
$http({
method: 'GET',
url: 'http://10.10.216.201:8080/Spring4/data/lworkflows'
}).then(function successCallback(response) {
var wfs = response.data;
var output = wfs.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
});
console.log(output);
var table=$('#example1').DataTable(
{
"data":output,
"columns": [
{ "className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '' },
null,
null,
null,
null,
null,
{ "orderable": false }
]
,
"order": [[ 1, "desc" ]]});
}, function errorCallback(response) {
console.log("error");
});
}

Categories