|
<script> |
|
document.addEventListener('DOMContentLoaded', function() { |
|
var table = new DataTable('#example', { |
|
scrollX: true, |
|
searching: false, |
|
scrollY: "600px", |
|
scrollCollapse: true, |
|
paging: false, |
|
fixedColumns: { |
|
leftColumns: 1 |
|
}, |
|
order: [ |
|
[2, 'asc'] |
|
], |
|
dom: 'Bfrtip', // enable export buttons |
|
buttons: [ |
|
{ |
|
extend: 'excelHtml5', |
|
text: 'Export Excel', |
|
title: 'weelko_products' |
|
}, |
|
{ |
|
extend: 'csvHtml5', |
|
text: 'Export CSV', |
|
title: 'weelko_products' |
|
}, |
|
{ |
|
text: 'Export JSON', |
|
action: function (e, dt, node, config) { |
|
// get column headers |
|
var headers = dt.columns().header().toArray().map(h => $(h).text().trim()); |
|
|
|
// map rows to objects using headers as keys |
|
var data = dt.rows({ search: 'applied' }).data().toArray().map(row => { |
|
var obj = {}; |
|
headers.forEach((h, i) => { |
|
let value = row[i]; |
|
|
|
// normalize numeric fields (prices, weight, volume, dimensions) |
|
if ( |
|
h.toLowerCase().includes("price") || |
|
h.toLowerCase().includes("weight") || |
|
h.toLowerCase().includes("volume") || |
|
h.toLowerCase().includes("height") || |
|
h.toLowerCase().includes("length") || |
|
h.toLowerCase().includes("width") |
|
) { |
|
if (typeof value === "string") { |
|
value = value |
|
.replace(/[^\d,.-]/g, "") // remove symbols like € or spaces |
|
.replace(",", "."); // replace comma with dot |
|
value = parseFloat(value) || 0; |
|
} |
|
} |
|
|
|
obj[h] = value; |
|
}); |
|
return obj; |
|
}); |
|
|
|
// convert to formatted JSON |
|
var json = JSON.stringify(data, null, 2); |
|
|
|
// create a blob and force download |
|
var blob = new Blob([json], { type: "application/json" }); |
|
var url = URL.createObjectURL(blob); |
|
var a = document.createElement("a"); |
|
a.href = url; |
|
a.download = "weelko_products.json"; |
|
a.click(); |
|
URL.revokeObjectURL(url); |
|
} |
|
} |
|
] |
|
}); |
|
}); |
|
</script> |