How to show data from get request in datatable? - javascript

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");
});
}

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 use Kendo UI on Multi Select with Search using Post API

I have added Kendo UI on multi-select and use Post API to fetch the data on the basis of the search.
Here is the code in which I have tried to implement it.
var searchx = ""
var ds = new kendo.data.DataSource({
transport: {
read: {
url : "https://searchapi/list",
type: 'POST',
data: function (params) {
console.log("1");
var searchTerm = params.term && params.term != "" ? params.term : searchx;
var query = {
"txt": [
{
"txt: "Level4",
"values": [
"1819"
]
},
{
"txt": "Level3",
"values": []
},
{
"txt": "Level2",
"values": []
},
{
"txt": "Leve1",
"values": [
"278"
]
}
],
"xyz": [
{
"dt": "2022-04-24",
"field": "startDate"
},
{
"dt": "2022-05-24",
"field": "endDate"
}
],
"sorts": [],
"limit": 50,
"q": searchTerm
}
searchx = searchTerm;
console.log("2");
console.log(JSON.stringify(query));
return JSON.stringify(query);
//return Json(ds, JsonRequestBehavior.AllowGet);
},
contentType: 'application/json',
dataType: 'json',
success: function(data){
},
datatype: "json",
beforeSend: function (xhr) {
console.log('beforeSend');
xhr.setRequestHeader('Authorization','Bearer #Session.AuthToken~');
}
}
},
serverFiltering: true,
serverSorting: true,
placeholder: "Select One..."
});
$("#Tasks").kendoMultiSelect({
placeholder: "Select Tasks...",
filter: "contains",
autoBind: false,
dataValueField: "objectId",
dataTextField : "title",
dataSource : ds
});
Autocomplete / Typeahead search . I have created a Multi-select control by using kendo.The Multi-Select is not working Can anybody can help me with this

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

dataTables Change Data for ajax call

I'm using the following function to load a DataTables table with data from the server. I would like to reload the table with different parameters on a click event only i cant work out how to do this. If i call reload it just reloads with the original parameters if i reinitialise the whole table it throws an error as the table already exists.
I have been looking into fnServerParams but cant work out if it would help or not.
If anyone can point me in the correct direction that would be great.
function LoadRiskProfileModalTable(userId, teamId, riskProfileClass) {
var params = {
userId: userId,
teamId: teamId,
riskProfileClass: riskProfileClass
};
var data = JSON.stringify(params);
//if (!$.fn.DataTable.isDataTable("#riskProfileTable")) {
var table = $("#riskProfileTable").DataTable({
"bProcessing": true,
"sAjaxSource": "WFMHome.aspx/GetRiskProfileDrillThroughDatatable",
"fnServerData": function (sSource, aoData, fnCallback) {
//aoData.push(JSON.stringify(params));
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": data,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
appendAlert("errorAlertPlaceholder", xhr.responseText, 1, "danger");
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
},
"columns": [
{ "data": "CaseHandler" },
{ "data": "caseAreaText" },
{ "data": "RiskProfileText" },
{ "data": "PassChecks" },
{ "data": "F1Checks" },
{ "data": "F2Checks" },
{ "data": "F3Checks" },
{ "data": "CurrentChecks" }
]
});
//}
//else {
// $('#riskProfileTable').DataTable().ajax.reload();
// }
};
If you just want to replace the data you have now by the data coming from the server, try to replace the success method by:
"success": function (msg) {
var json = jQuery.parseJSON(msg.d); //I assume it's the data set
var table = $("#riskProfileTable").DataTable();
table.rows.clear(); //clear the current data
table.rows.add(json).draw();
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},

Jquery Datatables Error: Invalid JSON primitive: draw

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

Categories