Issue on Loading Dynamic Data to "DataTables" Using jQuery - javascript

Demo
I am using this solution to load dynamic data in to Data Table. I have to use the Array of Array since I am getting dynamic data from user on font end selection (NO DATABASE Selection).
I am using following code to upload data into the table
<table cellpadding="0" cellspacing="0" border="0" class="dataTable" id="example"></table>
and JS:
$(document).ready(function () {
var counter = 0;
var compareTable = [];
var compareRow = [];
var check = "Test";
var compModelName = "Test";
var selectedType = "Test";
var selectedTarget = "Test";
var selectedROR = "Test";
var selectedSpecies = "Test";
var historicDis = "Test";
var projectsNumber = "Test";
var projectsCost = "Test";
var projectsRoads = "Test";
var projectsPowerline = "Test";
var projectsPenstock = "Test";
var mapshow = "Test";
$("#load").on("click", function () {
loader();
});
function loader() {
compareRow.push(check);
compareRow.push(compModelName);
compareRow.push(selectedType);
compareRow.push(selectedTarget);
compareRow.push(selectedROR);
compareRow.push(selectedSpecies);
compareRow.push(historicDis);
compareRow.push(projectsNumber);
compareRow.push(projectsCost);
compareRow.push(projectsRoads);
compareRow.push(projectsPowerline);
compareRow.push(projectsPenstock);
compareRow.push(mapshow);
}
$('#example').dataTable( {
"data": compareTable,
"columns": [
{ "title": "Compare" },
{ "title": "Model Name" },
{ "title": "Model Type" },
{ "title": "Energy Target" },
{ "title": "ROR Attribute" },
{ "title": "Species", "class": "center" },
{ "title": "Disturbance", "class": "center" },
{ "title": "Projects" },
{ "title": "Cost (M$)" },
{ "title": "Roads (Km)" },
{ "title": "Powerlines (Km)", "class": "center" },
{ "title": "Penstock (m)", "class": "center" },
{ "title": "Map" }
]
} );
});
});
but as you can see in the Demo it is not functioning when we click on the "#load". Can you please let me know why this is happening and how I can fix it?

Related

Looping through items in an object for google sheets

I am trying to loop through an array that is part of a JSON object from a page speed insights call to add all of the unused javascript Urls to a google sheet using the script editor.
Here is an example of the JSON object:
"audits": {
"unused-javascript": {
"id": "unused-javascript",
"title": "Remove unused JavaScript",
"description": "Remove unused JavaScript to reduce bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).",
"score": 0.43,
"scoreDisplayMode": "numeric",
"numericValue": 1350,
"numericUnit": "millisecond",
"displayValue": "Potential savings of 231 KiB",
"details": {
"type": "opportunity",
"headings": [
{
"key": "url",
"valueType": "url",
"subItemsHeading": {
"key": "source",
"valueType": "code"
},
"label": "URL"
},
{
"key": "totalBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceBytes"
},
"label": "Transfer Size"
},
{
"key": "wastedBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceWastedBytes"
},
"label": "Potential Savings"
}
],
"items": [
{
"url": "https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable",
"totalBytes": 140229,
"wastedBytes": 108197,
"wastedPercent": 77.15757011763822
},
{
"url": "https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js",
"totalBytes": 306716,
"wastedBytes": 106243,
"wastedPercent": 34.63892414884589
},
{
"url": "https://www.googletagmanager.com/gtm.js?id=GTM-KZ",
"totalBytes": 127214,
"wastedBytes": 21845,
"wastedPercent": 17.17151000374831
}
],
"overallSavingsMs": 1350,
"overallSavingsBytes": 236285
}
},
I am attempting to loop through the "items" array within the "unused-javascript" object and get all of the urls to show in google sheets.
Here is the code I have within the script editor. When I run this, only one URL shows on the sheet. However, I am trying to get all of the URLs added to the sheet.
function pageSpeed(Url) {
var key = "AIzaSyAyHY";
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
var firstmeaningfulpaint = content["lighthouseResult"]["audits"]["first-meaningful-paint"]["displayValue"].slice(0, -2);
var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
var unusedJs = content["lighthouseResult"]["audits"]["unused-javascript"]["details"]["items"];
for (var i = 0; i < unusedJs.items.length; i++) {
var unusedUrl;
unusedUrl = unusedJs[i]["url"]
}
}
else {
var timetointeractive = "An error occured";
var firstcontentfulpaint = "An error occured";
var firstmeaningfulpaint = "An error occured";
var speedindex = "An error occured";
var unusedJs = "An error occured";
}
}
var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');
array.push([timetointeractive, firstcontentfulpaint, firstmeaningfulpaint, speedindex, currentDate, "complete", unusedUrl]);
Utilities.sleep(1000);
return array;
}
}
Any and all help is appreciated!
You're on the right track.
Take a look below at my usage of Array.prototype.map. That's the simpler route.
Your for loop would work just as well IF you declared unusedUrl outside of (ie. before) the loop AND pushed to an existing array. As it is, there's an issue of scope, so unusedUrl is redeclared on every iteration, meaning you'll only assign the last iteration's value to unusedUrl.
Both solutions are below.
Using map
var content = {
lighthouseResult: {
audits: {
'unused-javascript': {
// Other stuff
details: {
// Other stuff
items: [
{
url:
'https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable',
totalBytes: 140229,
wastedBytes: 108197,
wastedPercent: 77.15757011763822,
},
{
url:
'https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js',
totalBytes: 306716,
wastedBytes: 106243,
wastedPercent: 34.63892414884589,
},
{
url: 'https://www.googletagmanager.com/gtm.js?id=GTM-KZ',
totalBytes: 127214,
wastedBytes: 21845,
wastedPercent: 17.17151000374831,
},
],
overallSavingsMs: 1350,
overallSavingsBytes: 236285,
},
},
},
},
}
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = items.map(item => item.url) // OR, using es6, items.map(({ url }) => url)
console.log(unusedUrls)
Using for
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = []
for (var i = 0; i < items.length; i++) {
unusedUrls.push(items[i]['url'])
}

jQuery DataTable add dynamic columns

I have a JSON object like below (dataSource) in that JSON object the property 'viewClasses' sometimes comes as blank, here what I want to do is if 'viewClasses' have any record I want to add a dynamic column to the table and the name of the column header will be the value of 'viewClasses.class', I have tried the below code but it's not working as expected.
Here is the result of the below code -
Here how I want this to be-
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var column = [];
function AddColumn() {
$.each(dataSource[0].viewDetails.viewClasses[0], function(key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
column.push(my_item);
});
}
$('#example').dataTable({
data: dataSource[0].viewDetails.viewClasses,
"columns": column,
"paging": false,
"bInfo": false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<style src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"></style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12">
<table id="example" class="table table-striped" width="100%"></table>
</div>
</div>
</div>
Your source data needs to be iterated in two different ways, to build the two different dynamic arrays which DataTables needs: - column data and row data.
Firstly you have two columns, A and B. To build the array for these, you can use the following:
var dynamicColumns = [];
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
});
I chose not to use the jQuery iterator because I want access to each object in the array.
This gives me the following structure:
[
{
"data": "A",
"title": "Heading A"
},
{
"data": "B",
"title": "Heading B"
}
]
But for the table's data, I want to end up with only one row of data:
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
Here, I end up with the following:
[
{
"A": 2000,
"B": 3000
}
]
Now I have the structures I need for my DataTable initialization. The overall script therefore is as follows:
<script type="text/javascript">
var dataSource = [{
"Name": "PI61890",
"portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
"StartDate": "2020-10-31T00:00:00",
"EndDate": "2020-10-31T00:00:00",
"processDate": "2020-10-31T00:00:00",
"viewDetails": {
"Name": "Management",
"Code": "MGMT",
"category": "Asset",
"description": "Asset Description",
"viewClasses": [{
"class": "A",
"amount": 2000.0
},
{
"class": "B",
"amount": 3000.0
}
]
},
}];
var dynamicColumns = [];
var dynamicRows = [];
function buildDynamicData() {
var columnData = dataSource[0].viewDetails.viewClasses;
var dynamicRow = {};
columnData.forEach(function (columnItem) {
// extract the column definitions:
var dynamicColumn = {};
dynamicColumn['data'] = columnItem['class'];
dynamicColumn['title'] = 'Heading ' + columnItem['class'];
dynamicColumns.push(dynamicColumn);
// extract the data set:
var field = columnItem['class'];
var value = columnItem['amount'];
dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);
}
buildDynamicData();
console.log(dynamicColumns);
console.log(dynamicRows);
$(document).ready(function() {
$('#example').DataTable({
columns: dynamicColumns,
data: dynamicRows,
paging: false,
info: false
});
} );
</script>
And the end result looks like this (in my test environment):

option selects from json object on categories

Hi (sorry for my english), I have this script:
<script type="text/javascript">
$(document).ready(function() {
var idPlato = decodeURI(getUrlVars()["idPl"]);
var url = "http://localhost/plato-datos.php?idPla="+idPlato+"";
});
};
</script>
It brings me this json from my database:
[{"category":"first","name":"green","idP":"1", "count":3},
{"category":"first","name":"blue","idP":"2","count":5},
{"category":"sec","name":"peter","idP":"3", "count":3},
{"category":"sec","name":"james","idP":"4", "count":2,},
{"category":"third","name":"dog","idP":"5", "count":4}]
I need to create one radiobuton for every name and group by categores
I create a solution. Kinda ugly but it will work:
var data = [{
"category": "first",
"name": "green",
"idP": "1",
"count": 3
}, {
"category": "first",
"name": "blue",
"idP": "2",
"count": 5
}, {
"category": "sec",
"name": "peter",
"idP": "3",
"count": 3
}, {
"category": "sec",
"name": "james",
"idP": "4",
"count": 2,
}, {
"category": "third",
"name": "dog",
"idP": "5",
"count": 4
}];
var result = {};
data.map(a => {
if (result[a.category]) {
result[a.category].push(a.name);
} else {
result[a.category] = [a.name];
}
});
Object.keys(result).map(category => {
var select = document.createElement('select');
result[category].map(name => {
var option = document.createElement('option');
option.value = name;
option.text = name;
select.appendChild(option);
});
document.body.appendChild(select);
});
Im working with jquery mobile then i used autodividersSelector function for group by the category JSON object, and build a radiobuton for every name
<script type="text/javascript">
//catch the JSON from my database
$(document).ready(function() {
var idPla = decodeURI(getUrlVars()["idPl"]);
var urlAder =
"http://localhost/lista-adereso.php?idPla=" + idPla + "";
//print the radiobutons
$.getJSON(urlAder, function(resultado) {
var allfiles = '';
for (var i = 0, aderesos = null; i <
resultado.length; i++) {
aderesos = resultado[i];
allfiles +='<li><label><input type="radio" data-
status="' + aderesos.aderesoCatNom +'"
name="name" id="id" value="' +
aderesos.aderNombre +'">'+
aderesos.aderNombre + '</label></li>'; }
//Group by categories
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('input').data("status");
return out;
}
})
.listview("refresh");
});
});
</script>

PhoneJs: update dynamically slideout

I would like to update a specific field in slideout from database(websql), to show the current user and he can access to his profil.
The targert is : title: log1, for that I used save:function (), and I have one record in database.
I spent many days searching but until now no solution.
Someone can help please.
Index
//...
<script type="text/javascript">
$(function() {
slideOut.app.navigate();
});
slideOut.Home = function (params) {
return {};
};
</script>
</head>
<body>
<div data-options="dxView : { name: 'Home', title: 'Slide Out' } " >
<div data-options="dxContent : { targetPlaceholder: 'content' } " >
</div>
</div>
</body>
</html>
App.config:
window.slideOut = $.extend(true, window.slideOut, {
var log1;
save:function (){
var db = openDatabase("dossierpatient", "1.0", "BD patient", 32678);
db.transaction(function(transaction){
transaction.executeSql("SELECT * FROM patient;", [], function(transaction,result){
for (var i=0; i< result.rows.length; i++) {
log1 = result.rows.item(i).login;
console.log(log1 + "\n ");
}
});
});
return log1;
}
"config": {
"navigationType": "slideout",
"navigation": [
{
"title": log1,
"action": "#",
"icon": "todo"
},
{
"title": "Item 2",
"action": "#",
"icon": "tips"
},
{
"title": "Item 3",
"action": "#",
"icon": "card"
},
{
"title": "Item 4",
"action": "#",
"icon": "map"
}
]
}
});
app.js
window.slideOut = window.slideOut || {};
$(function() {
// Uncomment the line below to disable platform-specific look and feel and to use the Generic theme for all devices
// DevExpress.devices.current({ platform: "generic" });
slideOut.app = new DevExpress.framework.html.HtmlApplication({
namespace: slideOut,
commandMapping: slideOut.config.commandMapping,
navigationType: "slideout",
navigation: getNavigationItems()
});
slideOut.app.router.register(":view", { view: "Home"});
function getNavigationItems() {
return slideOut.config.navigation; // cherche le contenu du slideOut
}
});
Seems like you have a mistake in app.config.js. The declaration of var log1 should be above extending code. The $.extend should have parameters as valid js objects:
var log1;
$.extend(true, window.slideOut, {
save: ...,
...
}
Move over I wouldn't advice you to add such a code in app config file.
To customize the view title (or whatever you have in your view) use viewModel with observables. For example:
slideOut.Home = function (params) {
var title = ko.observable("title");
var viewModel = {
title: title,
viewShowing: function() {
// TODO: put code fetching title from db and set it on done to observable
title("value");
}
};
return viewModel;
};
The code above will set the title of the view.

Getting complex attribute value of object

Given json like this :
{ "rss": {
"page": 1,
"results": [{
"type": "text",
"$": 10
}],
"text": [{
"content": "Lorem ipsum dolor sit amet.",
"author": {
"name": "Cesar",
"email": "cesar#evoria.com"
},
},
{
"content": "Tema Tis rolod muspi merol.",
"author": {
"name": "Cleopatre",
"email": "cleopatre#pyramid.com"
},
}]
}
In javascript, I can retrieve value like this :
var json = JSON.parse(datajson);
$.each(json.text, function(key, val) {
// this one is ok
var content = val['content'];
// this one does not work
var authorname = val['author.name'];
});
Is this a way, given the attribute name in a string format, to retrieve the value of a complex object, for instance json.text[0].author.name?
EDIT
I would like to store the needed attributes in another object like :
[
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name"}
]
You can split your "index" by . and loop over "segments", descending through levels on each iteration.
var obj = {
author : {
name : "AuthorName"
}
}
function get_deep_index(obj, index) {
var segments = index.split('.')
var segments_len = segments.length
var currently_at = obj
for(var idx = 0; idx < segments_len; idx++) {
currently_at = currently_at[segments[idx]]
}
return currently_at
}
console.log(get_deep_index(obj, 'author.name'))
The following should fix the problem.
var authorname = val['author']['name'];
You can also store the object itself as:
var author = val['author'];
And then later on you can index the attributes from that.
console.log(author.name, author.email)
Yent give a good hint in the comments with the eval function. I resolve my needed with this kind of code:
var json = JSON.parse(myjsonasastring);
var descriptiontobeadded = [
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name" }
];
$.each(descriptiontobeadded, function(key, val) {
var dt = '<dt>' + val.dt + '</dt>';
description.append(dt);
var dl = '<dd>' + eval('json.' + val.dd) + '</dd>';
description.append(dl);
});

Categories

Resources