I am trying to get some data from an API and load into Datatables (datatable.net). I have completed the code as per guide and it doesn't load at all.
AJAX completes the request successfully.
Code below:
function loadTable(api) {
$.ajax({
url: api,
type: 'GET',
dataType: 'json',
"dataSrc": "",
beforeSend: function () {
console.log('\"Data collection\" query operation triggered')
$(".overlay").show(); //We are showing loading spinner here
},
headers: { Authorization: 'Basic XXXX },
success: function (data, textStatus, xhr) {
//Populate Table
$('#datatable').DataTable({
"columns": [
{ "data": "DataObjectName" },
{ "data": "SourceObject" },
{ "data": "IndnexType" },
{ "data": "ObjectType" },
{ "data": "FeedType" },
{ "data": "BusinessUnit" },
{ "data": "VersionId" },
{ "data": "Unit" },
{ "data": "Unit" },
],
"bDestroy": true
})
console.log('\"Data collection\" query operation succesfully completed');
},
error: function (xhr, textStatus, errorThrown) {
console.log('\"Data collection\" query operation failed. Error : ' + errorThrown);
showNotification('top', 'right', 'Error while performing ' + operation + '. Error : ' + errorThrown, 'danger');
},
complete: function () {
$(".overlay").hide(); //We are showing loading spinner here
console.log('\"Data collection\" query operation task completed');
}
});
}
Related
I am very new to Datatables and this might be simple, but surely I am missing something. I am trying to create a button column that uses the filename of each row and uses it to make an ajax call to display a picture on click. What I get wrong is that, every button of the column displays the same image, and not the image of the filename for each row. Here is the code:
$.ajax ({
url: "http:// ...... /Services/DBPrintDatatable?customer_id=" + projectid,
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"aaSorting": [],
"columns": [
{ "data": "upload_date" },
{ "data": "filename" },
{ "data": "uploader" },
{ "data": "upload_place" },
{ "data": "is_ok" },
{ "data": "custom_verdict" },
{
data: { "data": "filename" },
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename='+ { 'data': 'filename' }>Show</a>";
}
},
] ,
});
Thank you in advance!
If the image url required is like
http://......./Services/DBShowImage?filename=filenameFromData
Then you should generate it first inside the render like below code
href='http://......./Services/DBShowImage?filename="+ row.filename+"';
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename="+ row.filename+"'>Show</a>";
}
No error but no data. Is there an option I need to add to make this work? my data uses the result from an ajax call.
Any suggestions?
Code:
$.ajax({
cache: false,
url: "http://a.co.nz/GetTestDocs",
data: '{'
+ ' "oldCompanyIdString": "' + selectOldCompanyId + '", '
+ ' "effectiveDateString": "' + selectEffectiveDate + '", '
+ ' "endDateString": "' + selectEndDate + '",'
+ ' "userToken": "' + userToken + '"'
+ ' }',
type: "POST",
//jsonpCallback: "Value",
contentType: "application/json",
dataType: "json",
error: function (jqXHR, textStatus, errprThrown) {
//console.log(errprThrown);
//window.location = location;
},
success: function (value) {
if (value.GetTestDocsResult != null) {
result = $.parseJSON(value.GetTestDocsResult);
if (result.length == 0) {
alert("Your query did not return any data.");
}
else {
console.log(result);
bindDataTable(result.DocsList);
}
}
}
});
function bindDataTable(data) {
$('#docuList').dataTable({
"processing": true,
"ajax": data,
"columns": [
{ "data": "Description" },
{ "data": "FileLocation" }]
});
}
Help pls..my first time to use dataTables
Replace "ajax": data, with "data": data,
function bindDataTable(data) {
$('#docuList').dataTable({
"processing": true,
"data": data,
"columns": [
{ "data": "Description" },
{ "data": "FileLocation" }
]
});
}
I have a DataSource in my code that support destroy. In order to delete object from the it, i directly call remove, i.e.
myDataSource.remove(discardedData);
I get a behavior similar to this. However, unlike the linked thread, my destroy is not set to a function, so the solution does not help me.
My DataSource (i included all of it in case some of my configuration is to blame):
var QueueMessages = {
type: "aspnetmvc-ajax",
transport: {
read: {
url: BASE_URL + "api/QueueMessages/GetMessagesHeaders",
dataType: "json",
type: "GET",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authService.getAuth());
}
},
destroy: {
url: BASE_URL + "api/QueueMessages/deleteMessage",
dataType: "json",
type: "DELETE",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authService.getAuth());
}
}
},
schema: {
model: {
id: "id",
fields: {
profileName: { type: "string" },
queueType: { type: "string" },
acceptedAt: { type: "date" },
processedAt: { type: "date" },
BodyExcerpt: { type: "string" }
}
},
total: "total",
data: "data",
},
error: function (e) {
//throw user back to login page
if (e.errorThrown === "Unauthorized")
$rootScope.$apply($location.path('/'));
},
requestStart: function () {
},
requestEnd: function () {
},
pageSize: 50,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
serverGrouping: true,
serverAggregates: true
};
I cant find any clues as to why this is happening.
thanks to OnaBai I found the problem.
consulting RFC 7231, i my changed the http DELETE response from 200 OK to 204 no content.
I have tried a host of REST endpoints in my app and all of them return access denied. I am baffled by this. I have double checked the app id and I know I am getting logged in. Here is the complete source:
<body>
<button onclick='post()'>Post on Yammer!</button>
<button onclick='loginStatus()'>Login Status</button>
<button onclick='postActivity()'>Post Activity</button>
<button onclick='getSuggestions()'>Get Suggestions</button>
<button onclick='getUser()'>Get User</button>
<button onclick='getMessages()'>Get Messages</button>
<button onclick='search()'>Search</button>`enter code here`
<button onclick='getGroups()'>Groups</button>
<script type="text/javascript">
//<![CDATA[
function post() {
yam.getLoginStatus(function (response) {
if (response.authResponse) {
alert(1);
yam.request({
url: "https://www.yammer.com/api/v1/messages.json",
method: "POST",
data: { "body": "HelloTest" },
success: function (msg) { alert("Post was Successful!: " + msg); },
error: function (msg) { Console.dir(msg);}
});
} else {
alert(2);
yam.login(function (response) {
if (!response.authResponse) {
yam.request({
url: "https://www.yammer.com/api/v1/messages.json",
method: "POST",
data: { "body": "HelloTest" },
success: function (msg) { alert("Post was Successful!: " + msg); },
error: function (msg) { Console.dir(msg); }
});
}
});
}
});
}
function loginStatus() {
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
alert("logged in");
console.dir(response); //print user information to the console
}
else { //authResponse = false if the user is not logged in, or is logged in but hasn't authorized your app yet
alert("logged out");
}
}
);
}
function postActivity() {
yam.request({
url: "https://www.yammer.com/api/v1/activity.json",
method: "POST",
data: {
"activity": {
"actor": {
"name": "Jeff Kirkham",
"email": "garthf#retailv3dev2.onmicrosoft.com"
},
"action": "create",
"object": {
"url": "https://www.yammer.com/retailv3dev2.onmicrosoft.com",
"title": "Lunch Meeting"
},
"message": "Hey, let’s get sushi!",
"users": [
{
"name": "Jeff Kirkham",
"email": "garthf#retailv3dev2.onmicrosoft.com"
}
]
}
},
success: function (msg) { alert("Post was Successful!: " + msg); },
error: function (msg) { console.dir(msg); }
})
}
function getUser() {
yam.request({
url: "https://www.yammer.com/api/v1/users/current.json",
method: "GET",
success: function (msg) { alert("Get was Successful!: " + msg); },
error: function (msg) { console.dir(msg); }
})
}
function getMessages()
{
yam.request({
url: "https://www.yammer.com/api/v1/messages.json",
method: "GET",
success: function (msg) { alert("Get was Successful!: " + msg); },
error: function (msg) { console.dir(msg); }
})
}
function search()
{
yam.request({
url: "https://www.yammer.com/api/v1/search.json",
method: "GET",
search: "Marketing",
success: function (msg) { alert("Get was Successful!: " + msg); },
error: function (msg) { console.dir(msg); }
})
}
function getGroups() {
yam.platform.request({
url: "groups.json?mine=1",
method: "GET",
data: {},
success: function (msg) { alert("Get was Successful!: " + msg); },
error: function (msg) { console.dir(msg); }
})
};
function getSuggestions() {
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
console.log("logged in");
yam.platform.request({
url: "suggestions.json", //this is one of many REST endpoints that are available
method: "GET",
data: { //use the data object literal to specify parameters, as documented in the REST API section of this developer site
"letter": "a",
"page": "2",
},
success: function (user) { //print message response information to the console
alert("The request was successful.");
console.dir(user);
},
error: function (user) {
alert("There was an error with the request.");
console.dir(user);
}
});
}
else {
alert("not logged in")
}
}
);
}
//]]>
</script>
<script data-app-id="gYLlvylCHqAYNiwAa40AHw" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js" type="text/javascript">
</script>
</body>
Note: Instead of plastering a really long script for everyone else to debug, it would be more helpful if you narrowed the scope of your script down to a single function that was not working as expected.
One point I noticed is that you are calling www.yammer.com/api/v1/.
We've restricted JS SDK calls to www.yammer.com/api/v1 endpoints due to CORS. Instead, omit the hostname and just focus on the endpoint like you've done in the suggestions.json example.
Main Problem
My current problem is the refresh progress when updating a grid datasource. I have change my code use the kendo.ui.progress in that way when requestStart event starts I ser the kendo.ui.progress to true. This activates the loading image when it end it calls the requestEnd.
The problem is that this event is hapenning for sorting and filtering. And I want it to only trigger for the read function of the dataSource. This problem makes the grid to use the progress endlessly.
Is there some way to filter in the requestStart and requestEnd only activate on the transport read?
My DataSource Code
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url_Obtener_Periodo,
type: "POST"
},
parameterMap: function (options, operation) {
if (operation == "read" && options) {
return {
"periodo.Year": $("#periodo-anio").val(),
"periodo.Month": $("#periodo-mes").val(),
"Filtro": $("#Filtro").val()
};
}
}
},
requestStart: function (e) {
kendo.ui.progress($("#grid-container"), true);
},
requestEnd: function (e) {
kendo.ui.progress($("#grid-container"), false);
},
schema:{
model: {
id: "Codigo_De_Pedido",
fields: {
Codigo_De_Pedido: { type: "number" },
Fecha_Y_Hora_De_Creacion: { type: "date" },
UserName: { type: "string" },
Nombre_Del_Usuario: { type: "string" },
Codigo_Del_Vendedor: { type: "number" },
Nombre_Del_Vendedor: { type: "string" },
Is_Pedido_Closed: { type: "bool" },
Estado: { type: "string" }
}
}
},
pageSize: 10
});
The changes I did to solve the progress endlessly problem where 2.
Removing requestEnd function from the dataSource
Adding dataBound function to the Grid
Data Source Code
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url_Obtener_Periodo,
type: "POST"
},
parameterMap: function (options, operation) {
if (operation == "read" && options) {
return {
"periodo.Year": $("#periodo-anio").val(),
"periodo.Month": $("#periodo-mes").val(),
"Filtro": $("#Filtro").val()
};
}
}
},
schema:{
model: {
id: "Codigo_De_Pedido",
fields: {
Codigo_De_Pedido: { type: "number" },
Fecha_Y_Hora_De_Creacion: { type: "date" },
UserName: { type: "string" },
Nombre_Del_Usuario: { type: "string" },
Codigo_Del_Vendedor: { type: "number" },
Nombre_Del_Vendedor: { type: "string" },
Is_Pedido_Closed: { type: "bool" },
Estado: { type: "string" }
}
}
},
pageSize: 10,
requestStart: function (e) {
kendo.ui.progress($("#grid-container"), true);
}
});
Kendo Grid Code
kendoGrid = $("#selectable-pedidos").kendoGrid({
dataSource: dataSource,
pageable: true,
sortable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Comienza Con",
eq: "Es Igual A",
neq: "No Es Igual A"
}
}
},
dataBound: function (e) {
kendo.ui.progress($("#grid-container"), false);
},
columns: [
{ field: "Fecha_Y_Hora_De_Creacion", title: "Fecha y Hora", template: "#= kendo.toString(Fecha_Y_Hora_De_Creacion, 'dd/MM/yyyy hh:mm:ss tt') #" },
{ field: "Codigo_De_Pedido", title: "Código de Pedido" },
{ field: "Estado", filterable: true, title: "Estado" },
{ field: "Codigo_Del_Vendedor", title: "Código de Vendedor" },
{ field: "Nombre_Del_Vendedor", title: "Nombre de Vendedor" },
{
command: {
text: "Ver Detalle de Pedido",
click: function (e) {
$("#empty").append("<form method='POST' action='/HojaDeRuta/GetById/'><input type='hidden' name='Codigo_Pedido' value='"
+ this.dataItem($(e.currentTarget).closest("tr")).Codigo_De_Pedido + "' /><input type='submit' /></form>");
$("#empty input[type='submit']").click();
}
},
title: " "
}
]
}).data("kendoGrid");
There are a few things about your questions worth mentioning for those who read this:
Is there some way to filter in the requestStart and requestEnd only
activate on the transport read?
Yes, but it will not help you. The parameter of the event has a type property that will contain read, update, destroy or create.
statementEntriesDS.bind("requestStart", function (e) {
switch (e.type) {
case "create":
alert('-> event, type "create".');
break;
case "read":
alert('-> event, type "read".');
break;
case "update":
alert('-> event, type "update".');
break;
case "destroy":
alert('-> event, type "destroy".');
break;
}
});
Your example code doesn't specify serverFiltering or serverSorting so sorting and filtering wouldn't cause an remote action. You'll only get client-side sorting and filtering. However, if they are specified they're all going to result in a read and that wouldn't really help you.
That you would not have the requestEnd event fire sounds odd. You should probably add a handler for the error event and see if something is failing.
If you really want complete control over what's happening, you can specify a function for your read:
transport: {
read: function (options) {
kendo.ui.progress($gridContainer, true);
$.ajax({
url: carrierServiceBaseUrl + "/GetManualStatementsCarrierList",
contentType: 'application/json; charset=utf-8',
dataType: "json",
type: "POST",
success: function (result) {
// notify the data source that the request succeeded
options.success(result);
kendo.ui.progress($gridContainer, false); },
error: function (result) {
options.error(result); // Call the DataSource's "error" method with the results
kendo.ui.progress($gridContainer, false);
notification.show({
title: "ERROR:",
message: result.statusText
}, "error");
}
});
}
}