dataTables Change Data for ajax call - javascript

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

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

Retrieving data from db.json file and adding it into an array using javascript

I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}

Render Process is Gone in Google Chrome While adding 100,000 rows to a DataTable

Im loading 100,000 rows of data from my php BackEnd using Ajax as follow:
First an ajax call get the number of rows , pages "chunks" and the total of records to load from a click event (I already try with 10K rows to 50K rows and everything works ok).
$('#btnObtenerData').on('click', (e) => {
$.ajax({
url: 'getData.php',
type: 'GET',
dataType: 'JSON',
data: {
"accion": "getConteo"
}
}).done((response) => {
totalPaginas = response.totalPaginas,
totalFilas = response.totalFilas;
console.log(totalPaginas, totalFilas);
if (totalPaginas > 0) {
cargarPaginas(totalFilas, totalPaginas);
}
})
});
Once the first call is done cargarPaginas is executed, this function contains the followed code.
function cargarPaginas(totalFilas, totalPaginas) {
//paginar(1,totalFilas,totalPaginas);
let arr = [];
let pages = totalPaginas;
for (var i = 0; i < totalPaginas; i++) {
console.log(totalPaginas);
arr.push({
page: i + 1,
rows: totalFilas,
pages: pages
});
}
var p = $.when();
arr.forEach(function(item, key) {
p = p.then(function() {
return paginar(item.page, item.rows, item.pages);
});
});
}
And getPagina y paginar run the followed code as well
function getPagina(numeroPagina) {
let pagina = $("#paginacion").find('a.activa');
$("#tbodyReporte").find("[data-pagina='" + numeroPagina + "']").css("display", "");
$("#tbodyReporte").children("tr[data-pagina!='" + numeroPagina + "']").css("display", "none");
$(pagina).trigger('click');
}
function paginar(paginaNumero = 1, totalFilas = 1000, totalPaginas = 0) {
return $.ajax({
url: 'getData.php',
type: 'GET',
dataType: 'JSON',
data: {
accion: "getData",
"numeroPagina": paginaNumero,
"numeroFilas": totalFilas
}
}).done((response) => {
console.log(response);
if (paginaNumero == 1) {
tabla = $('#gridReporte').DataTable({
data: response,
columns: [{
"data": "Factura"
},
{
"data": "Tipo de Servicio"
},
{
"data": "SERVICIO"
},
{
"data": "fecha de emision"
},
{
"data": "NContrato"
},
{
"data": "CLIENTE"
},
{
"data": "Tipo Pago"
},
{
"data": "CIUDAD"
},
{
"data": "COLONIA"
},
{
"data": "Oficial de Recuperacion"
},
{
"data": "MONEDA"
},
{
"data": "MORA"
},
{
"data": "Cargo por Servicio"
},
{
"data": "ISV"
},
{
"data": "Total Factura"
},
{
"data": "N Cliente"
},
{
"data": "Dia Mora"
},
{
"data": "NUMRECIBO"
},
{
"data": "Agente Mant Cartera"
},
{
"data": "Nombre Vendedor"
},
{
"data": "Clase Cliente"
},
{
"data": "Tipo Vendedor"
}
],
dom: 'Bfrtip',
buttons: [
'excelHtml5'
],
"language": idioma_spanol,
"pageLength": 500,
"columnDefs": [{
"targets": '_all',
"createdCell": function(td, cellData, rowData, row, col) {
$(td).css('padding', '1px');
$(td).css('margin', '0px');
}
}]
});
} else {
tabla.rows.add(response)
.draw();
}
})
}
Like I said when a load of 50K records or less is made everything goes well
But when I try to load more than 90K records the Browser Tab crash like this:
I would like to understand why is this happening? and How to fix it.
Thanks in advice

for each, item[i].id isnt working. any ideas?

Done this before in the past.
But having issues with this again
Trying to get the ids from a fb page using the api from fb
Here is an example of the outputted json.
{
"data": [
{
"created_time": "2019-01-10T05:50:49+0000",
"message": "hello world",
"id": "233542"
},
{
"created_time": "2019-01-10T05:50:48+0000",
"message": "hello world",
"id": "454524"
},
{
"created_time": "2018-12-24T06:19:31+0000",
"message": "hello world",
"id": "399434"
}
]
}
Script
var key = "(insert fb api here)";
<!-- facebook api get -->
var getkey = "https://graph.facebook.com/v3.2/(insert fb id here)/feed?access_token=" + key;
$.ajax({
type: 'GET',
url: (getkey),
contentType: 'application/json',
dataType:'jsonp',
responseType:'application/json',
xhrFields: {
withCredentials: true
},
headers: {
'Access-Control-Allow-Credentials' : true,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'GET',
'Access-Control-Allow-Headers':'application/json',
},
success: function(data) {
$.each(data, function (i, item) {
console.log(item[i].id);
});
},
error: function(error) {
console.log("error");
}
});
one way iv found that works is
console.log(item[0].id);
How ever this just console logs the first of the nested json,
Am I missing something?
Any help is appreciated.
try this :
$.each(data.data, function (i, item) {
console.log(item.id);
});

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