how can I get value from google spreadsheet - node.js

I need to get value from Google spreadsheet iframe, only one cell (A2) that I display on website.
This value (10%) I want to transfer to progress bar (style="width: [value from google spreadsheet]").
Is it possible?
Thanks!
EDIT:
I've add API and it works very well, I can show values in CMD, so now I want to get this value and transfer to my website. Any suggestions?
const GoogleSpreadsheet = require('google-spreadsheet');
const { promisify } = require('util');
const creds = require('./client_secret.json');
function printInfo(my_sheet){
console.log(`Name: ${my_sheet.kontrahent}`);
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('ID');
await promisify(doc.useServiceAccountAuth)(creds);
const info = await promisify(doc.getInfo)();
const sheet = info.worksheets[4];
console.log(`Title: ${sheet.title}, Rows: ${sheet.rowCount}`);
const rows = await promisify(sheet.getRows)({
offset: 1
});
console.log(rows[0].kontrahent); <!--I want get this value and transfer it to my div progress bar on HTML -->
rows.forEach(row => {
printInfo(row)
});
}
accessSpreadsheet();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>My test page</title>
</head>
<body>
<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vST98KwaC1TPrCA-I-t7DrtL6dcjiFt1K1300c2j57N-SbcYRA2r4akTE_QxuStIvky39bedioEx-Tr/pubhtml?gid=0&single=true&range=A2&widget=false&headers=false&chrome=false" height="40px" width="226px"></iframe>
<div class="progress">
<div class="progress-bar progress-bar-success" style="width: 80%"></div>
</div>
</body>
</html>

iFrame interaction is kinda complicated and unsafe. A better way to tackle this problem is using the Google Sheets API.
Here is the basic reading section: https://developers.google.com/sheets/api/samples/reading
You would need the following components:
Google API key
Something to do a basic REST request

Related

Couls someone explain why i get this error? "TypeError: Cannot read property 'split' of undefined"

I'm new to Node js and i have a function that receives a json object with numeric values, that i try to add up and display the result on the browser using a "Sum" property. The problem occurs at the mathsServer.js (split() method in the addera()). I do not understand why i suddenly get this error especially when i modified my code according to a MVC. When i run it independently in one file it worked well at some point. Here is my code.
Im supposed to POST a json in postman:
{
"tal": "10,343,24,345,22,23,233, 45, 200,500"
}
router.js:
const express = require("express");
const router = express.Router();
const controller = require("./controllers/controller");
router.post("/add", controller.renderSum)
router.get("/add",controller.renderSum)
module.exports = router
controller.js:
const mathServerModel = require("../../../mathServer/model/mathModel");
exports.renderSum = (req, res) => {
mathServerModel.addera(req.body.tal)
.then(function (data) {
console.log(data);
//res.send({data});
res.render("post-tal", {
Sum: {data} // A property called Sum to be displayed on the browser
})
})
.catch(error => console.log(error))
}
mathModel.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const addera = async (tal) => {
let strNumbersArr = tal.split(","); // ["10", "343", "24", ..., "233"]
let sum = 0;
for(let i = 0; i < strNumbersArr.length; i++) {
let currentNumberStr = strNumbersArr[i];
sum += Number(currentNumberStr); // convert current number string into a number
}
return sum;
}
module.exports = {
addera
}
index.hbs
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>WebApp</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
<link rel="stylesheet" type="text/css" href="../css/style.css">
<style>
.eNavAction {cursor:pointer}
.buttons {margin-top: 20px}
</style>
<script src="js/simple-helper.js"></script>
<script src="model/customer-model.js"></script>
<script src="view/customer-view.js"></script>
<script src="controller/main-controller.js"></script>
<script>
var Current = {};
const Model = new TeamsModel();
const View = new TeamView();
const ViewTal = new TalView();
const Controller = new MainController();
document.addEventListener('DOMContentLoaded', function() {
// Controller.init();
Helper.onClassClick('eNavAction',Controller.navAction);
});
</script>
</head>
<body>
<nav class="navbar is-link" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a class="navbar-item" href="/">
<span style="font-weight:bold; font-size:20px" href="http://127.0.0.1:3000/">My Web App</span>
</a>
</div>
<div id="navbar" class="navbar-menu">
<div class="navbar-start">
<a class="eNavAction navbar-item" action ="teams" href="http://127.0.0.1:3000/">Teams</a>
<a class="navbar-item" action= "tal">Sum</a>
</div>
</div>
</nav>
<div class="section">
<div id="main-container">
<div class="enterTal">
<div class="displaySum">
<p>Sum is: {{Sum}}</p>
</div>
</div>
</div>
</div>
</body>
</html>
It appears in controller.js req.body doesn't have an object tal (req.body.tal). You must start your investigation there. mathServerModel.addera() call is passing Undefined object as parameter.
In mathsServer.js, make your code defensive, by first checking your parameters' validity. Check if they have the values and types you were expecting before going into your function's logic.

Question about incrementing data value, from a specific collection in mongodb with nodejs

So I followed a tutorial which has taught me some things about nodejs and mongodb. I now know how to insert new data from the server in to my database.
But what I can't seem to figure out is how to update existing data in a collection. I have searched on a lot of places but sadly no clear answer for me. I am a little of a noob still with this so excuse me if i say things that are probably wrong.
So this is what I've tried to set up:
Code from my Controller.js:
app.get("/button", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
db.numbers.update({ $inc: { number: -2}})
getData(res);
})
})
}
I am using the MVC model that has the: controller, model and view. So all pages in the view folder are .ejs files. I am also using jQuery and ajax to send a request to the controller.
button.js:
$(document).ready(function(){
$('#btn1').on('click', function(){
var number = {number: 0}
$.ajax({
type: 'GET',
url: '/button',
data: number,
success: function(number){
//do something with the data via front-end framework
location.reload();
alert('It works')
}
});
});
})
button.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="/assets/button.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo List</title>
<link href="/assets/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Button test</h1>
<button id="btn1">Increase number</button>
</body>
</html>
So basically what I am trying to achieve is that once I press a button somewhere on a page, it would increase/decrease a value in the database in one of the specific collections. I am kinda lost with this, any help would be appreciated.
After searching for a very long time, i finally found the solution. If anyone else is having this issue then refer to this link: https://docs.mongodb.com/drivers/node/usage-examples/updateOne

Simple SVG project cause error on Internet Explorer 11

I am learning svg and would like to compare displaying svg items on different browsers. My code works fine on firefox, chrome, edge, safari etc, but cannot work on ie11. Unfortunately application I develop needs to support ie11 so I need to force my code to work correctly.
Here is fiddle: https://jsbin.com/hemawaboqa/1/edit?html,js,output
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/#svgdotjs/svg.js"></script>
</head>
<body>
<div style="position:absolute;left:0px;top:0px;right:0px;bottom:0px;overflow:hidden;" id="svg-main-container">
<div style="position:absolute;left:0px;top:0px;bottom:0px;right:300px;border:1px solid #dadada;overflow:auto;" id="svg-canvas"></div>
</div>
</body>
</html>
JS
var draw = SVG().addTo('#svg-canvas').size(400, 400)
var rect = draw.rect(100, 100)
Why that code is not working on ie11?
I have created a sample using the SVG.js 3.0 version with your code, it will show the "Object doesn't support property or method 'from'" in IE11 browser, perhaps the issue is related to the svg.js version, and it is a plugin issue, you could feedback this issue to SVG.js forum.
Besides, I suggest you could refer to the following code, to use the old version of SVG.js:
<!DOCTYPE html>
<html lang=en-us>
<head>
<meta charset=utf-8>
<title>TEST</title>
</head>
<body>
<div style="position:absolute;left:0px;top:0px;right:0px;bottom:0px;overflow:hidden;" id="svg-main-container">
<div style="position:absolute;left:0px;top:0px;bottom:0px;right:300px;border:1px solid #dadada;overflow:auto;" id="drawing">
</div>
</div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js></script>
<script>
(function () {
'use strict';
// Add title as first child of SVG element:
var createTitle = function (svgObject, text) {
var fragment = document.createDocumentFragment();
var titleElement = document.createElement('TITLE');
fragment.appendChild(titleElement);
titleElement.innerHTML = text;
svgObject.node.insertAdjacentElement('afterbegin', titleElement);
};
SVG.extend(SVG.Doc, {
namespace: function () {
return this
.attr({xmlns: 'http://www.w3.org/2000/svg', version: '1.1'})
.attr('xmlns:xlink', SVG.xlink, SVG.xmlns);
}
});
var draw = new SVG('drawing').size(300, 300);
var rect = draw.rect(100, 100).attr({fill: '#f06'});
// Add title to SVG element
createTitle(draw, 'Rectangle');
}());
</script>
</body>
</html>
The result as below:
The library you are using has ECMA 6 elements that are not understood in IE.
If you need your project to work in IE, you will have to use another library or find out how to change it so it allows for older browsers (as suggested here: https://svgjs.dev/docs/3.0/compatibility/)

gmplot Google Maps html output not showing markers/heatmap

I am running gmplot in Pycharm (2018.1 Community) with Python Interpreter 3.5.4 (via Anaconda 1.5).
gmplot definitely creates the map.html, and the lat/longs are listed in the html.
However it does not appear to be plotting the lat/long on the image.
What am I missing?
Python Code:
gmap = gmplot.GoogleMapPlotter(lats[0],longs[0],15) #working
gmap.heatmap(lats, longs) #not working
gmap.draw('map.html')
HTML Output:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - pygmaps </title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"></script>
<script type="text/javascript">
function initialize() {
var centerlatlng = new google.maps.LatLng(40.218483, 29.042473);
var myOptions = {
zoom: 15,
center: centerlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var heatmap_points = [
new google.maps.LatLng(40.218483, 29.042473),
new google.maps.LatLng(40.218500, 29.042485),
###....(for the sake of brevity - removed)....
new google.maps.LatLng(40.220540, 29.043019),
new google.maps.LatLng(40.220569, 29.043032),
new google.maps.LatLng(nan, nan),
];
var pointArray = new google.maps.MVCArray(heatmap_points);
var heatmap;
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
heatmap.set('threshold', 10);
heatmap.set('radius', 10);
heatmap.set('opacity', 0.600000);
heatmap.set('dissipating', true);
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
Image opened by browsing to the HTML file on my local machine: (no markers!)
Map
And when I try to open the html file direct from PyCharm, I get Javascript errors that look like this:
Firefox Javascript console
This happens regardless of whether I use gmplot.scatter or gmplot.heatmap.
Do I need to put an API key somewhere?
Any ideas?

views.player widget for artists

i'm trying to get the player view working for an artist, but bar hacking around/manually reimplementing is there a better way to do this. below is the code that i have tried so far, taken from a stack overflow regarding the same thing for albums.. There is two problems with this, one the image doesn't show up/fallback to the album and two, when you try and play you get "Uncaught TypeError: Object Tin Hat Trio has no method 'get' "
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="sp://import/css/eve.css">
<link rel="stylesheet" href="sp://import/css/api.css">
</head>
<div id="artist-element"></div>
<script>
var sp = getSpotifyApi(1);
var views = sp.require('sp://import/scripts/api/views');
var models = sp.require('sp://import/scripts/api/models');
models.Artist.fromURI('spotify:artist:5spC5WtEkxDbaIH7bGGX4m', function(artist) {
var p = new views.Player();
p.context = artist;
document.getElementById('artist-element').appendChild(p.node);
});
</script>
</body>
</html>
The player object can only have a context of type Album or Playlist. Documentation here.

Resources