Retrieve Data From Google Scripts - javascript

I wrote a custom Google Script which outputs an object for me and I would like to be able to call it and assign it to a variable which is then used to display data on a website.
Currently, I have figured out to access the data using another Google Scripts project, however I can't find a way to do it using something like a JS file on my computer or DreamHost server.
This is what I have tried:
var infected_data = getData();
function getData() {
var URL = 'https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec';
var response = UrlFetchApp.fetch(URL);
return response;
}
on something like playcode.io it gives me the following error:
error: Uncaught ReferenceError: UrlFetchApp is not defined
I get the same thing just putting it on my computer and running it there with Chrome:
It appears UrlFetchApp is only for within Google Scripts. Is there some other way to access the output outside of the Google environment.
*I don't know how authorization and all that fits in here (because Google Scripts seems to run it as my user. right?)
HTML Header:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>JQVMap - World Map</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="../dist/jqvmap.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../dist/jquery.vmap.js"></script>
<script type="text/javascript" src="../dist/maps/jquery.vmap.world.js" charset="utf-8"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.deaths.js"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#ffffff',
hoverOpacity: 0.8,
selectedColor: '#3498DB',
enableZoom: true,
showTooltip: true,
scaleColors: ['#F3A291', '#FF4F3B'],
values: infected_data,
normalizeFunction: 'polynomial',
onLabelShow: function (event, label, code) {
label.html('<div class="map-tooltip"><h1 class="header"> ' + label.html() + '</h1><p class="description">Infected: ' + infected_data[code] + '</p><p class="description">Deaths: ' + death_data[code] + '</p></div>');
}
});
});
</script>
</head>
Google Scripts File:
function doGet() {
var result = {};
var infected = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getDataRange().getValues();
var death = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getDataRange().getValues();
result = makeObject(infected);
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON);
}
function makeObject(multiArr) {
var obj = {};
var countrystats = {};
var headers = multiArr.shift();
for (var i = 0; i < headers.length; i++) {
countrystats[i] = multiArr.map(function (app) {
return app[i];
})
}
for (var m = 0; m < countrystats[1].length; m++) {
obj[countrystats[1][m]] = 0;
}
for (var j = 0; j < countrystats[1].length; j++) {
var TempVar;
TempVar = obj[countrystats[1][j]];
obj[countrystats[1][j]] = TempVar + countrystats[3][j];
}
return obj;
}
Google Scripts Output (using the JSON View chrome extension):
{
cn: 8134,
th: 23,
mo: 7,
us: 5,
jp: 11,
kr: 4,
sg: 10,
vn: 2,
fr: 5,
np: 1,
my: 8,
ca: 3,
ci: 1,
lk: 1,
au: 9,
de: 4,
fn: 1
}
This is a public link with the object/data i want on it (the same object shown above):web app: https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec
So basically anyone who uses it should be able to access it. I just need a way to assign that data to a local JS variable. The google sheets script is published as a web app. If I'm not mistaken there is a setting to allow anyone, even anonymous to access it.
Here is my attempt at an AJAX request:
var url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
var infected_data = jQuery.ajax({
crossDomain: true,
url: url,
method: "GET",
//dataType: "jsonp"
});
If i uncomment the jsonp I get an error:
jquery-1.11.3.min.js:5 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://script.googleusercontent.com/macros/echo?user_content_key=JXkCjiJjhcjndRREjoGyVNkZNkD-HvKpEPkpicQBm9nR9OkxjGXdYuOPsLxbJf-B9Rgifl5NWMtzgjfVGuMdGxTJrjKnRpdcOJmA1Yb3SEsKFZqtv3DaNYcMrmhZHmUMWojr9NvTBuBLhyHCd5hHazTNYZyoqG0ZuVXpWSNdoeLErB4AfUCNPKJHgELe5WaAmN5SlwIhonlWkkbFzR8kUwjKrMtdq9u-YqreD7W_KJ_aVqKVBTehAuogPCoZCfVc4yJf5ieDCdMDbXQ8FZZq8iSedsk1Px1LnPBLM8W-ZRcknnbJNT8dS525XG1pNEBR&lib=Mw_Scq3iKhByBS86NJpd_CngcdEShCw7K with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
I don't get any errors if i remove it. However, i still can't see the data on my interactive map (My application).

If you are trying to get data from a Google Spreadsheet from outside of Google Apps Script, like on your own website/server, you will need to use the Sheets API.
Here is a good article on how to make Google API calls using JavaScript: https://medium.com/google-cloud/gapi-the-google-apis-client-library-for-browser-javascript-5896b12dbbd5.

const url = "PUT YOUR GOOGLE WEB APP URL HERE";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
)
return await DataJSON
};

Related

How to "p5.js loadJson"(read json) in html file without http request and write fs to json file?

How Do i debug this in order for me to read and write in json file to html without http request?
I have already got the answer from my previous question project "How to use push() into array json file when "mouse click"?" but now I can't even load/read file from json to html by using my p5.js loadjson project, do i missing something? or do I doing it wrong by arrange my code in the right order?
this is my previous answer project>
How to use push() into array json file when "mouse click"?
my project use for p5.js loadjson>
How to Debug "P5.js + Node.js with Parse Json" file
//my code>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sketch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="libraries/p5.min.js"></script>
<script src="libraries/p5.sound.min.js"></script>
</head>
<body>
<script src="sketch8.js"></script>
</body>
</html>
sketch8.js
function preload() {
winston = loadJSON("Data2.json");
}
function setup() {
createCanvas(400, 400);
}
function draw() {
//JSON parse & fs read Node.js
// var fs = require('fs');
// var data = fs.readFileSync('Data2.json');
// var winston = JSON.parse(data);
// console.log(winston);
//Test Terminal
/*
node sketch7.js
*/
{
if (mouseIsPressed) {
winston.xPositions.push(mouseX);
} else {
var data = JSON.stringify(winston, null, 2);
fs.writeFileSync('Data2.json', data, finished);
function finished(err) {
console.log('all set.');
}
}
stroke(64, 117, 207);
fill(196, 33, 255);
for (var i = 0; i < winston.xPositions.length; i++) {
line(winston.xPositions[i], 120, 194, 285);
ellipse(winston.xPositions[i], 104, 32, 46);
}
}
fill(0, 0, 0);
textSize(16);
text("Winston likes " + winston.likes[0] + " and " + winston.likes[1], 10, 90);
};//<
Data2.json
{
"likes": ["programming", "being programmed"],
"xPositions": [100, 200]
}
//<my code
After remove the else statement
if I remove the else statement then I can read json file, but that will remove reason to write, I want to "read and write" to json file to html
if (mouseIsPressed) {
winston.xPositions.push(mouseX);
} /*else {
var data = JSON.stringify(winston, null, 2);
fs.writeFileSync('Data2.json', data, finished);
function finished(err) {
console.log('all set.');
}
}
*/ //<else write data to json
The reason i use node without http request cause of this code that I use>
//node code>
app.js
//Create New File 2>>
var fs = require('fs');
fs.readFile('readMe.txt', 'utf8', function(err, data){
fs.writeFile('writeMeMe22.txt', data, function(err, result) {
if(err) console.log('error', err);
});
});
//Terminal
//node app
readMe.txt
ya here???
//<node code
as you can see when i use terminal and type node app or node app.js, It create a new file when read file AKA read and write with node, the new file can also be json file as well, like writeMeMe22.txt > writeMeMe22.json
//new file>
writeMeMe22.txt
ya here???
//<new file
Since sketch8.js is running in a web browser you are not going to be able to use fs.writeFileSync() which is a Node.js function intended for use on the server side. Instead you will want to use saveJSON() to initiate a file download.

Including JS file returns html content

I am facing this problem, and i cannot figure it out. Its simple thing, i need to include my js file into a head. But in my page I've got error Uncaught SyntaxError: Unexpected token '<' in ShopData.js:1 . So I've checked that file in chrome inspector, and i see that there is no JS content inside of it. It basically clone the html file and include it as js. How this can even happen and what is the solution? In ShopData.js is pure JS content, no includes or something. I've already checked permissions for that files and set it to read/write but no result, whole page is in domain hosting. Thanks for any advice.
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="ShopData.js"></script>
</head>
JS File:
var ShopID = 0;
var Name = "";
var City = "";
var Street = "";
var PostCode = "";
var State = "CZ";
var Longitude = "";
var Lattitude = "";
var Email = "";
var Telephone = "";
var Tittle = "";
var Description = "";
var Keywords = "";
var Barbers;
var OpeningHours;
var ItemTypes;
var Items;
let ShopData = {};
jQuery.ajax({
type: "GET",
url: "https://example.com/",
dataType: "json",
success: function(response) {
console.log(response);
}
});
Screenshot of response
This file isn't valid JavaScript so it will give that error:
https://barber.minuto.cz/web/ShopData.js
Also it seems to give that response no matter which URL you type in:
https://barber.minuto.cz/web/asdfasdf
Also you may want to make it so everyone can't login here since it is out in public now:
https://barber.minuto.cz

Unable to Connect to Spotify Api :Error Invalid URI Response

I am using the following two files attached.
index2.html file located on the local server which is calling the JavaScript file which is also located on the local machine
fetch-ajax3.js - JavaScript file located on the local server consisting of the function and method to authenticate and authorize the API call and retreive data and post it in the console.
I am not sure what to input in redirect URI.
Can someone help?
Resolution - i was able to resolve the issue after whitelisting the callback uri in the spotify api app.
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = '';
const redirectUri = '';
const scopes = [
'user-top-read'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url: "https://api.spotify.com/v1/me/top/artists",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $('<li>' + artist.name + '</li>');
item.appendTo($('#top-artists'));
});
}
});
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="./fetch-ajax3.js" defer></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</body>
</html>
After whitelisting the callback url in the app , i was able to connect it.
specify your URL as Http for localhost in the app settings in your Spotify dashboard
You need to add your URL in Redirect URI which will whitelist your URL. It works for me.

Passing value to target webpage using phantomjs

I am using Phantomjs. I need to pass certain information to the webpage (http://localhost:4569/index.html) we are targeting. The idea is, as soon as the target page loads, pass a JSON object to page & set it a globally accessible variable. Something like window.data = {....}. Once this variable is set, the target page will make use of this variable. Is it possible to get the desired result using Phantomjs?
var webPage = require('webpage');
var page = webPage.create();
var settings = {
operation: "POST",
encoding: "utf8",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
some: "data",
another: ["custom", "data"]
})
};
page.open('http://localhost:4569/index.html', settings, function(status) {
console.log('Status: ' + status);
//
One way that you might be able to facilitate this is a combination of setInterval and injectJs(). I would check for the data in the target page every few seconds. Then I would inject in a piece of data using injectJs. Then I would digest the injected data and have the phantomjs script react accordingly.
index.html
<html>
<head>
<title>Phantest</title>
</head>
<body>
<main>
<h1>Phantom Test</h1>
<p>Test of phantom</p>
</main>
<script>
(function () {
console.log("Hello");
setInterval(function () {
if (window.myVar) {
console.log("window.myVar is here!");
console.log(window.myVar);
}
}, 1000);
}());
</script>
</body>
</html>
phan.js
/*jslint node:true*/
"use strict";
var page = require("webpage").create();
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.open("http://127.0.0.1:52987/index.html", function (status) {
if (status === "success") {
page.injectJs("inject.js");
}
});
inject.js
/*jslint browser:true devel:true*/
console.log("I'm from Phantom");
window.myVar = "I'm myVar!";

How to send a cross-domain POST request using ajax call in c#

I am developing an application in which from a website project I give a call to web api method using ajax call javascript. When I run both projects locally it works fine, but when I do publish web api project on demo site the ajax call does not reach to the web api method.
My ajax call is as follows-
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function () {
var url = 'http://abc.demo.in/c60/api/Patient/Create/';
$.ajax({
url: url,
data: getData(),
type: 'POST',
contentType: "application/json",
success: function (result) {
console.log(result);
alert("success")
},
error: function (result) {
alert('POST failed.');
}
});
function getData() {
var patient = new Object();
patient.Name = "Mugdha";
patient.Gender = "Female";
patient.Email = "mugdhaShenoy#yahoo.co.in";
patient.Mobile = "";
patient.BloodGroup = "AB+";
patient.MedicalHistory = "High BP, Cholosterol, Diebetis";
patient.Allergy = "Dust, wind";
patient.EmergencyContactName = "Riya Sahani";
patient.EmergencyContactNo = "9988990200";
patient.ProfileImage = "";
patient.FormNo = "92";
patient.BirthDate = new Date(1989, 09, 08).toISOString();
return patient;
}
</script>
</head>
<body>
</body>
</html>
When I try to reach the api domain(which is on different server) I have faced an error as -
XMLHttpRequest cannot load http://abc.demo.in/c60/api/Patient/Create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:49370' is therefore not allowed access.
Is there any solution for this? I have added CorsHandler.cs file in my webapi project.

Categories