jquery datatable receive incorect json from webAPI - javascript

i can't populate a jQuery Datatble from ajax command.
this is webAPI code (UtentiController):
' GET: api/Utenti
<HttpGet>
Public Function GetUtentis() As IEnumerable(Of Utenti)
Using WFe As WorkForceEntities = New WorkForceEntities
Return WFe.Utentis.ToList
End Using
End Function
this is client side code:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
paging: true,
sort: true,
searching: true,
"ajax": {
"url": '/api/utenti/',
"type": "get",
"datatype": "json",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
},
"columns": [
{ "data": "Nome", "autoWidth": true },
{ "data": "Cognome", "autoWidth": true },
{ "data": "Username", "autoWidth": true },
{ "data": "GruppoDiLavoro", "autoWidth": true },
{ "data": "ProfiloFunzionalità", "autoWidth": true },
]
})
})
</script>
i think the problem is on json string. the ajax command return incorrect json, missing the initial substring {"data":
[
{
"IDutente": 2,
"Operatore": "Admin",
"Password": "1234",
"LivelloDiAccesso": 1,
"Nome": "Admin",
"Cognome": "Admin",
"Username": "Admin",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
},
{
"IDutente": 3,
"Operatore": "MS",
"Password": "1234",
"LivelloDiAccesso": 2,
"Nome": "Admin",
"Cognome": "S",
"Username": "M",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
}
]
if i load a json file like this ("ajax": "../UtentiData.json",)
{
"data": [
{
"IDutente": 2,
"Operatore": "Admin",
"Password": "1234",
"LivelloDiAccesso": 1,
"Nome": "Admin",
"Cognome": "Admin",
"Username": "Admin",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
},
{
"IDutente": 3,
"Operatore": "MS",
"Password": "1234",
"LivelloDiAccesso": 2,
"Nome": "Admin",
"Cognome": "S",
"Username": "M",
"GruppoDiLavoro": "Admin",
"ProfiloFunzionalità": "Admin",
"Attivo": true,
"DataCreazione": "2017-08-30T00:00:00",
"DataScadenza": "2025-12-31T00:00:00",
"Mail": "nothing"
}
]
}
the code work well and the jQuery Datatable is populate correctly.
what can i do to work fine with Json webAPI?
thanks

you could use a "Flat array data source".
Change your code to:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
paging: true,
sort: true,
searching: true,
"ajax": {
"url": '/api/utenti/',
"type": "get",
"dataSrc": "",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
},
"columns": [
{ "data": "Nome", "autoWidth": true },
{ "data": "Cognome", "autoWidth": true },
{ "data": "Username", "autoWidth": true },
{ "data": "GruppoDiLavoro", "autoWidth": true },
{ "data": "ProfiloFunzionalità", "autoWidth": true },
]
})
})
See the example.

Related

How to reduce repetition in Javascript code?

I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.
Here's the JS Code
<script type="text/javascript">
function parseDate(date) {
if (!date) {
return ""
}
return new Date(parseInt(date.substr(6))).toLocaleString();
}
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
$("#getAll_wrapper").addClass("w-100");
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllSentByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data?.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllSentToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllFailedByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllFailedToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
</script>
Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.
Update, suggestion from #Roamer-1888 finally I try this and it works!
function renderTable(action, tableId) {
$.ajax({
"url": action,
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$(tableId).DataTable({
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
}
$(document).ready(function() {
renderTable("#Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
renderTable("#Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
renderTable("#Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});

Strapi: trouble populating multi-valued attribute for nested relation

I have a collection called dish-category which contains many dishes, and a dish collection that contains many dish-options (another collection).
the list of dishes from each dish-category is available in the API but the nested collection of dish options from each dish is not available on strapi.
the following are the settings for my models:
dish-category.settings.json:
{
"kind": "collectionType",
"collectionName": "dish_categories",
"info": {
"name": "DishCategory",
"description": ""
},
"options": {
"increments": true,
"timestamps": true,
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"Name": {
"type": "string"
},
"Description": {
"type": "text"
},
"dishes": {
"collection": "dish",
"via": "dish_category"
}
}
}
dish.settings.json:
{
"kind": "collectionType",
"collectionName": "dishes",
"info": {
"name": "Dish",
"description": ""
},
"options": {
"increments": true,
"timestamps": true,
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"Name": {
"type": "string"
},
"Description": {
"type": "text"
},
"Total": {
"type": "decimal",
"min": 0,
"required": false,
"default": 0
},
"dish_categories": {
"collection": "dish-category"
},
"dish_options": {
"collection": "dish-option",
"via": "dish"
},
"dish_category": {
"via": "dishes",
"model": "dish-category"
}
}
}
dish-option.settings.json:
{
"kind": "collectionType",
"collectionName": "dish_options",
"info": {
"name": "DishOption",
"description": ""
},
"options": {
"increments": true,
"timestamps": true,
"draftAndPublish": true
},
"pluginOptions": {},
"attributes": {
"Name": {
"type": "string"
},
"Price": {
"type": "decimal",
"min": 0,
"default": 0
},
"dish": {
"via": "dish_options",
"model": "dish"
}
}
}
on the dish-category/controllers/dish-category.js file I tried populating the attribute:
'use strict';
/**
* Read the documentation (https://strapi.io/documentation/developer-docs/latest/development/backend-customization.html#core-controllers)
* to customize this controller
*/
module.exports = {
async find(params, populate){
return strapi.query('dish-category').find(params, ["dishes","dish.dish_options"]);
}
};
I am having trouble displaying nested relations with multiple values, I have tried looking up solutions online, I came across this thread https://forum.strapi.io/t/simple-nested-array-issue/1045/4 but the solution doesn't work for me and it seems like the link to the example is no longer available.

For Stripe Connected Accounts, which part of the account.updated webhook object indicates that the account is enabled?

I have an endpoint that is receiving events from Connected Stripe accounts. The webhook listens for the account.updated event type. It works as expected. However, when I look at the object sent to my endpoint, I'm not sure what would indicate that the account is in "enabled" status. I ask because if the Connected account was successfully set up, I would like to then give the customer the ability to access their Stripe dashboard. If it's not, then I would want for them to be able to finish the account setup process. Any insight would be appreciated. This is what I get from the Stripe webhook:
{
"id": "EXAMPLEID",
"object": "event",
"account": "ACCOUNT",
"api_version": "2020-03-02",
"created": 1608614938,
"data": {
"object": {
"id": "ACCOUNTNUMBER",
"object": "account",
"business_profile": {
"mcc": null,
"name": null,
"support_address": null,
"support_email": null,
"support_phone": null,
"support_url": null,
"url": null
},
"capabilities": {
"transfers": "active"
},
"charges_enabled": true,
"country": "US",
"default_currency": "usd",
"details_submitted": true,
"email": null,
"payouts_enabled": true,
"settings": {
"bacs_debit_payments": {
},
"branding": {
"icon": null,
"logo": null,
"primary_color": null,
"secondary_color": null
},
"card_payments": {
"statement_descriptor_prefix": null,
"decline_on": {
"avs_failure": false,
"cvc_failure": false
}
},
"dashboard": {
"display_name": "Books For Everyone",
"timezone": "Etc/UTC"
},
"payments": {
"statement_descriptor": null,
"statement_descriptor_kana": null,
"statement_descriptor_kanji": null
},
"sepa_debit_payments": {
},
"payouts": {
"debit_negative_balances": true,
"schedule": {
"delay_days": 2,
"interval": "daily"
},
"statement_descriptor": null
}
},
"type": "express",
"created": 1608614884,
"external_accounts": {
"object": "list",
"data": [
{
"id": "ID_NUMBER_HERE",
"object": "bank_account",
"account": "ACCOUNT_NUMBER_HERE",
"account_holder_name": null,
"account_holder_type": null,
"available_payout_methods": [
"standard"
],
"bank_name": "STRIPE TEST BANK",
"country": "US",
"currency": "usd",
"default_for_currency": true,
"fingerprint": "x9ELfUw7u81waQkl",
"last4": "6789",
"metadata": {
},
"routing_number": "110000000",
"status": "new"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/accounts/ACCOUNT_NUMBER/external_accounts"
},
"login_links": {
"object": "list",
"total_count": 0,
"has_more": false,
"url": "/v1/accounts/ACCOUNT_NUMBER/login_links",
"data": [
]
},
"metadata": {
},
"requirements": {
"current_deadline": null,
"currently_due": [
],
"disabled_reason": null,
"errors": [
],
"eventually_due": [
"individual.dob.day",
"individual.dob.month",
"individual.dob.year",
"individual.ssn_last_4"
],
"past_due": [
],
"pending_verification": [
]
},
"tos_acceptance": {
"date": 1608614937
}
},
"previous_attributes": {
"capabilities": {
"transfers": "inactive"
},
"charges_enabled": false,
"details_submitted": false,
"payouts_enabled": false,
"requirements": {
"currently_due": [
"tos_acceptance.date",
"tos_acceptance.ip"
],
"disabled_reason": "requirements.past_due",
"eventually_due": [
"individual.dob.day",
"individual.dob.month",
"individual.dob.year",
"individual.ssn_last_4",
"tos_acceptance.date",
"tos_acceptance.ip"
],
"past_due": [
"tos_acceptance.date",
"tos_acceptance.ip"
]
},
"tos_acceptance": {
"date": null
}
}
},
"livemode": false,
"pending_webhooks": 1,
"request": {
"id": "ID_NUMBER_HERE",
"idempotency_key": null
},
"type": "account.updated"
}
Because there are now multiple things an account might be used for, there isn't necessarily one single attribute to check for being "enabled" overall. Mostly you'll want to look at the capabilities (docs, API reference) such as in your data where you see transfers: 'active', which indicates that account is currently enabled for transfers.
You'll also want to keep an eye on the requirements hash (docs, API ref), which is how Stripe will inform you that additional information is needed now (or eventually).

How to load Datatables from JSON object directly on Ajax success result?

After long time searching here around I can't find a solution to this problem, loading Datatables via Ajax GET is well documented but how can I use directly a JSON response after an Ajax POST?
This is my PHP function:
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}
The JSON on success looks like this:
{
"data": [{
"#": "1",
"id": "9",
"art": "default\/def8.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla vita",
"tag": "riflessioni,vita,",
"likes": "1",
"views": "1024",
"duration": "185",
"time": "2015-11-30 19:36:31"
}, {
"#": "2",
"id": "15",
"art": "default\/def2.jpg",
"name": "Simon The Cat",
"title": "Riflessioni sulla morte",
"tag": "riflessioni,morte,",
"likes": "1",
"views": "1003",
"duration": "185",
"time": "2015-11-14 12:06:21"
},
...]
}
I also tried this:
//from this:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url':jQuery.parseJSON(html),
"dataSrc": ""
},
...
//to this:
$('#example').DataTable( {
"ajax": jQuery.parseJSON(html),
...
But on console it always shows me the error "lenght of undefined".
I already tried to load data directly from a JSON file url
containing the same response here above and it works well.
How can I load JSON data on Ajax POST success results to populate my table?
Finally, after many tries, I found the solution that works with the latest Datatables release (1.10.13):
function getRelated() {
var elements = (document.getElementsByClassName('exashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
//parse as string
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
//html is a json_encode array so we need to parse it before using
var result = jQuery.parseJSON(html);
$('#example_ert').DataTable( {
//here is the solution
"data": result.data,
"ajax": {
"url": result,
"dataSrc": ""
},
"columns" : [
{ "data": "#" },
{ "data": "id" },
{ "data": "art" },
{ "data": "name" },
{ "data": "title" },
{ "data": "tag" },
{ "data": "likes" },
{ "data": "views" },
{ "data": "duration" },
{ "data": "time" }
]
});
}
});
}

How to add edit functionality in datatable with bootstrap and MVC

I have done following code and now iI want to add edit column in Bootstrap Datatable with server side functionality in MVC and Bootstrap. Finally I want proper CRUD operation, so how can I approach for this?
<script type="text/javascript">
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
dt = $('#assets-data-table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "#Url.Action("Get","Asset")"
},
"columns": [
{ "title": "ID", "data": "ID", "searchable": true },
{ "title": "Name", "data": "Name", "searchable": true },
{ "title": "City", "data": "City", "searchable": true },
{ "title": "EmpCode", "data": "EmpCode", "searchable": true },
{ "title": "DOJ", "data": "DOJ", "searchable": true },
{ "title": "Address", "data": "Address" },
{ "title": "DOB", "data": "DOB" }
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
}
}
// initialize the datatables
assetListVM.init();
});
</script>

Categories