I'm trying to use DataTables with a success callback. Because I want to give a user a warning if the values they entered that creates a DataTable has an error.
Unfortunately, DataTables requires success callback for themselves, hence I cannot overload it.
Currently the code is:
configurationBlockChart = $('#blockSearchTable').DataTable(
{
processing: true,
serverSide: true,
stateSave: true,
bDestroy: true,
ajax:
{
type: 'GET',
url:"ajax_retreiveServerSideBlockNames/",
data:
{
'csrfmiddlewaretoken':csrftoken,
'username':username
}
},
rowCallback: function(row, data)
{
if ($.inArray(data.DT_RowId, blockSelected)!== -1)
{
$(row).addClass('selected');
}
},
});
The data that is returned by this Ajax Get are rows of data.
However, there is a possibility that the data returned has a response of invalid, with no rows returned
I tried to add success before rowCallBack:
success: function(response)
{
if(response.status == "invalid")
//then inform user
}
Also tried to use fnDrawCallBack
fnDrawCallback: function(settings, response)
{
console.log("Hello World!");
if(response.status == "invalid")
{
$('#invalid').modal("show");
$('#usernameSearch').modal("show");
}
}
However, the fnDrawCallBack will only call if there are rows returned.
The problem is that sometimes that no rows are returned, and an exception is given by the javascript code.
I could, however, do a try catch, but I would still like my server to give json statuses to the javascript code.
EDIT: With using xhr, it could catch that invalid response while in the meantime does not interfere with the success function for ajax.
$('#chartSearchUsername').click(function(event)
{
$('#chartConfigModal').modal("hide");
$('#usernameSearch').modal("show");
configurationUserChart = $('#userSearchTable').DataTable(
{
processing: true,
serverSide: true,
stateSave: true,
bDestroy: true,
ajax:
{
type: 'GET',
url:"ajax_retreiveServerSideUsernames/",
data:
{
'csrfmiddlewaretoken':csrftoken
},
},
rowCallback: function(row, data)
{
if ($.inArray(data.DT_RowId, userSelected)!== -1)
{
$(row).addClass('selected');
}
},
})
.on('xhr.dt', function(e, settings, response)
{
if(response.status == "invalid")
{
$('#invalid').modal("show");
$('#usernameSearch').modal("hide");
}
});
});
$('#example').dataTable();
$('#example').on( 'xhr.dt', function () {
console.log( 'Ajax call finished' );
} );
jQuery datatables is coded to use the success callback in ajax and it breaks if you intercept it. Source
You can also make use of jQuery ajax dataFilter callback.
$('table[id=entries]').DataTable({
processing: true,
serverSide: true,
ajax: {
type: 'POST',
url: 'http://example.com/entries',
dataFilter: function(response) {
var json_response = JSON.parse(response);
if (json_response.recordsTotal) {
// There're entries;
}else{
// There're no entries;
}
return response;
},
error: function (xhr) {
console.error(xhr.responseJSON);
}
}
});
Note: Return a String, not JSON in dataFilter callback.
Related
I am trying to load the jQuery DataTable from an AJAX call as in the code below. However I need to know if there is a callback for the DataTable to check if the AJAX call returned successfully or failed before the table is loaded.
$(function() {
$('#data-table').DataTable({
destroy: true,
responsive: true,
serverSide: false,
autoWidth: false,
paging: true,
filter: true,
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [5, 10, 25, 50, 75, 100],
ajax: {
url: 'https://jsonplaceholder.typicode.com/todos',
type: 'GET',
dataSrc: ''
},
columns: [{
title: 'Zone',
data: 'LastKnownZone',
}, {
title: 'HiƩrarchie Map',
data: 'MapInfo.mapHierarchyString',
}, {
title: 'Addresse MAC',
data: 'macAddress',
}],
initComplete: function(json) {
let returned_data = json;
//..Do something with data returned
}
});
});
Appreciate any help.
Just adding something to #Fawaz Ibrahim's answer, it's also better to add error option in Ajax call in order to check if you face any error or problem , because in case of error, dataSrc callback won't run, so you won't have any successful returned data.
ajax: {
...
dataSrc: function ( receivedData ) {
console.log('The data has arrived'); // Here you can know that the data has been received
return receivedData;
},
error: function (xhr, error, thrown) {
console.log('here you can track the error');
}
}
As it is mentioned on their official site:
For completeness of our Ajax loading discussion, it is worth stating
that at this time DataTables unfortunately does not support
configuration via Ajax. This is something that will be reviewed in
future
But you can use the idea of datasrc, like this:
$(function() {
$('#data-table').DataTable({
...
ajax: {
...
dataSrc: function ( receivedData ) {
console.log('The data has arrived'); // Here you can know that the data has been received
return receivedData;
}
},
...
});
});
I am trying to show results not found message when there's no suggestion from user input. typeahead.js shows input suggestion while giving input to text field..if there no suggestion found then how to show results not found message?.. version is typeahead.js 0.11.1
You can check if no result with empty parameter:
I have edited above code a little bit so that it may help to others searching the same thing.
$('.typeahead').typeahead({
hint: false,
highlight: true,
minLength: 3,
},
{
name: 'firstnames',
displayKey: 'value',
source: firstnames.ttAdapter(), // this is your result variable
templates: {
empty: function(context){
// console.log(1) // put here your code when result not found
$(".tt-dataset").text('No Results Found');
}
}
I have the same issue. But i'm using ajax for my source not adapter. You can try adding popover if suggestions length is 0.
function BindControls_facility(facility_names,facility_details,id) {
var timeout;
$('#facility_names'+id).typeahead({
items: "all",
// source: facility_names,
source : function (query, result) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$.ajax({
url: master_url + "/facility_name_dropdown_list",
method: 'POST',
xhrFields: {
withCredentials: false
},
data: { input_query : query},
success: function (data) {
if(Object.keys(data.facility_name).length > 0){
// $("#facility_names"+id).popover('destroy');
result($.map(data.facility_name, function (item) {
return item;
}));
}
else{
$('#facility_names'+id).popover({container: '#botdiv'+id,placement: 'top'}).popover('show');
$('#facility_names'+id).attr('data-content','No result found for \"'+$("#facility_names"+id).val()+'\"').data('bs.popover').setContent();
setTimeout(function () {
$('#facility_names'+id).popover('destroy');
}, 2000);
}
}
});
}, 300);
},
hint: true,
highlight: true,
cache: true,
compression: true,
minLength: 3,
updater: function(item) {
var details = "";
$.ajax({
url: master_url + "/get_facility_name",
method: 'POST',
xhrFields: {
withCredentials: false
},
data: { facility_name : item},
success: function (data) {
console.log(data.status);
}
});
return item;
}
});
}
I tried showing this "no results found" warning using bootstrap-popover. I know its not a good one to try but i just shared my way to achieve this if i had the same issue.
I'm using datatable to show list from database mysql
I need to update some input on end of table loading, then I'm using success function but this seems to prevent data rendering
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
},
// EDIT this "my" success function
success: function( data ) {
$('#my_input').val(data.return);
}
}
Json returned is:
{
"data":[[ (datatable value) ]],
"returned":"myvalue"
}
here the jsfiddle
EDIT
http://jsfiddle.net/ntcwust8/95/
Datatable has its own complete event thats called initComplete.
If you redefine success you are overriding Datatable's own function.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
....
....
},
'initComplete':function(settings, json){
alert($('#example tbody tr').length+ ' records on screen');
});
Reference: https://datatables.net/reference/option/initComplete
Update fidle: http://jsfiddle.net/ntcwust8/94/
Just remove the success callback.
success - Must not be overridden as it is used internally in
DataTables. To manipulate / transform the data returned by the server
use ajax.dataSrc (above), or use ajax as a function
Datatable by default handles the success callback, Don't override it.
Instead use complete option of AJAX to do something after data loading.
Updated fiddle
You just need to remove success callback.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
}
}
Edit
you need to use ajax.dataSrc property it will call after ajax finish.
It will work on refresh as well
https://datatables.net/reference/option/ajax.dataSrc
var table = $('#example').DataTable({
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
},
"dataSrc": function (json) {
$("#mydata").val(json.recordsTotal);
return json.data;
}
},
});
here is updated fiddle.
http://jsfiddle.net/2jkg3kqo/2/
Not only should this be a straightforward operation but I'm following the documentation as well. I have an ajax call that returns a json data set. I've cleared the table successfully but when the success method is called nothing happens. The console statement shows that data is being returned... however the table remains empty. Any idea why?
JS
$('#SortByCoverage').click(function () {
var table = $('#theTable').DataTable();
table.fnClearTable();
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#thetable").dataTable({
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
Server Side Code
public JsonResult Question2()
{
var ads = _client.GetAdDataByDateRange(new DateTime(2011, 1, 1), new DateTime(2011, 4, 1));
var json = ads.Where(x => x.Position.Equals("Cover") && x.NumPages >= (decimal)0.5).Select(x => new{
AdId = x.AdId,
BrandId = x.Brand.BrandId,
BrandName = x.Brand.BrandName,
NumPages = x.NumPages,
Position = x.Position
});
return Json(json, JsonRequestBehavior.AllowGet);
}
Sample Data (client side)
EDIT
As pointed out in the comments I misspelled the element name dataTable in the success callback. However, now I'm getting the following error:
Cannot reinitialise DataTable. To retrieve the DataTables object for this table, pass no arguments or see the docs for bRetrieve and bDestroy
Do I really have to destroy the table, once it's clear, to reload the data?
I added the bRetrieve and bDestroy. This got rid of the error but still no new data loaded into the table.
$.ajax({
url: '#Url.Action("Question2", "Home")',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log(data);
$("#theTable").dataTable({
//"bRetrieve": true,
"bDestroy": true,
"aaData": data,
"aoColumns": [
{title:"AdId"},
{title:"BrandId"},
{title:"BrandName"},
{title:"NumPages"},
{title:"Position"}
]
});
}
});
I would make a little different, see how:
var theTable = $("#thetable").dataTable({
"aaData": [],
"aoColumns": [
{data:"AdId"},
{data:"BrandId"},
{data:"BrandName"},
{data:"NumPages"},
{data:"Position"}
]
}).DataTable();
$('#SortByCoverage').click(function () {
$.ajax({
url: '/Home/Question2',
type: 'GET',
dataType: 'json',
success: function (data) {
theTable.clear().draw();
table.rows.add(data)
.draw();
}
});
I am trying to implement jQuery autocomplete using the approach illustrated below (i.e. a separate source function and an intermediary variable for the data). Right now I'm trying to get the data to the source part of the autoComplete function.
The code below works with one fatal issue, the very first key stroke returns an undefined returnData variable. Can any one explain what's going on?
var returnData;
function sourceFn() {
return $.ajax({
url: //REST URL,
dataType: "jsonp",
async: false,
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
returnData = data;
},
})
}
}
$("input#search-input").bind("autocompleteselect", jQuery.proxy(function (event, ui) {}, this)).autocomplete({
appendTo: "#yt-result-list",
source: function (request, response) {
sourceFn(request, response).done(alert("returnData: " + JSON.stringify(returnData)));
}
}).data("autocomplete")._renderItem = jQuery.proxy(function (ul, item) {
alert(item);
}, this)
});
});
});
Try specifing the minLength: 0 when initializing the autocomplete, check the value of returnData to see if you get the json back from the server (use firebug).
Looks like you're not getting from the ajax call with one letter only, the autocomplete is triggering sourceFn() correctly.