We have a very simpel Google Apps Script Web App, which purpose is to show JSON data in a HTML drop-down-list. The JSON file exists in Google Drive. Inspiration code from: http://jsfiddle.net/manoj_admlab/Mta5b/3/
But when we are trying to 'Fetch Json' no data is loaded in to the dropdown-list:
index.html
<!DOCTYPE html>
<html>
<br> <br>
<center>
<head>
<base target="_top">
</head>
<body>
<select id="destinations">
<option value="">Select</option>
</select>
Fetch JSON
</center>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
google.script.run.getJson(); // Runs the function "getJson();" in Code.gs
$('#fetch').click(function(s) {
$.post(s, {json: JSON.stringify(json)}, function(data) {
$.each(data.Destinations, function(i, v) {
$('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
});
});
});
</script>
</body>
</html>
Code.gs
function doGet() {
var template = HtmlService.createTemplateFromFile('index');
var htmlOutput = template.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
function getJson() {
var files = DriveApp.getFilesByName("jsonData.json");
var file = files.next();
var JSONDATA = file.getAs("application/json").getDataAsString();
//JSONDATA = JSON.stringify(JSONDATA);
JSONDATA = JSON.parse(JSONDATA);
Logger.log(JSONDATA);
click(JSONDATA); // <-- Trying to pass this data to "$('#fetch').click(function(s) {"
}
jsonData.json
{
"options": {
"Destinations": [
{
"destinationName": "London",
"destinationID": "lon"
},
{
"destinationName": "New York",
"destinationID": "nyc"
},
{
"destinationName": "Paris",
"destinationID": "par"
},
{
"destinationName": "Rome",
"destinationID": "rom"
}
]
}
}
You have to return the data in getJson() function, and when calling it, you need to pass a callback, with withSuccessHandler(), as such:
in HTML:
function justLog(e){
console.log(e);
}
$('#fetch').click(function(s) {
google.script.run.withSuccessHandler(justLog).getJson(); // Runs the function "getJson();" in Code.gs
});
in code.gs, finish the function with:
return JSONDATA;
Thanks Kriggs! This worked out great:
Index.html:
<!DOCTYPE html>
<html>
<head>
<select id="dropDownDest">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
function onSuccess(json) {
$.each(json.Cars, function (key, value) {
$("#dropDownDest").append($('<option></option>').val(value.carID).html(value.CarType));
});
$('#dropDownDest').change(function () {
alert($(this).val());
//Code to select image based on selected car id
});
}
google.script.run.withSuccessHandler(onSuccess)
.jsonData();
</script>
</head>
</html>
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function jsonData() {
var a = {
Cars: [{
"CarType": "BMW",
"carID": "bmw123"
}, {
"CarType": "mercedes",
"carID": "merc123"
}, {
"CarType": "volvo",
"carID": "vol123r"
}, {
"CarType": "ford",
"carID": "ford123"
}]
};
Logger.log(a);
return a;
}
Related
I am using hbs as view in frontend.
I tried to send data to my script in html from nodejs like this :
router.get('/home',authController.isLoggedIn, (req ,res) => {
if(req.user){
db.query('SELECT * FROM posts ORDER BY id desc ', (error,results) => {
if (error) {
console.log(error);
} else {
let categories;
db.query('SELECT * FROM categories', (error,result) => {
if (error) {
console.log(error);
} else {
console.log(result);
categories = result;
return res.render('home',{
results: results,
categories: categories
});
}
});
}
});
}else {
res.redirect('/login');
}
});
then when i am trying to call it here in script using javaScript it tells me something is wrong
<script>
alert(results);
</script>
I want to know how correctly call the the object in script
edit:
the data should be something like this :
[
RowDataPacket { id: 1, category: 'Music' },
RowDataPacket { id: 2, category: 'Memes' },
RowDataPacket { id: 3, category: 'Tech' }
]
For EJS example if pass data msgs:
res.render("index.ejs", {
msgs
})
js handle data:
<p>
<%
msgs = msgs.map(function(msg) {
return '<div>' + msg.name + '</div>' + '<div>' + msg.msg + '</div>'+ '<div>' + msg.time + '</div>'
})
%>
</p>
print directly:
<p><%- msgs.join("<hr />") %></p>
save in global variable
<script>
window.serverMsgs = <%- msgs %>;
</script>
And for handlebars:
<script>
window.serverMsgs = {{msgs}};
alert(window.serverMsgs)
{{#each results}}
{
"id": {{id}},
"category": "{{category}}",
}
{{#unless #last}},{{/unless}}
{{/each}}
</script>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>{{title}} - Page Test</title>
</head>
<body>
<div class="description">{{description}}</div>
<ul>
{{#datas}}
<li class="item" id="item_{{index}}"><span>{{time}}</span>{{title}}</li>
{{/datas}}
</ul>
</body>
</html>
u could check out this similar issue:) How to define an array within a <script> tag inside a hbs view template
So I have this HTA Application I'm working on, Which will be used in remote locations where there will be little to no internet. Its should be very basic as in I just want it to load/read a json file and edit/append some fields within the JSON file. If I load it within a web browser by changing the extention to .html it works and reads the json no problem, when I rename it back to .hta and execute its just blank. I dont understand why.
testJSON.hta
<html>
<head>
<title>TEST - JSON Editor</title>
<HTA:APPLICATION ID="oHTA" APPLICATIONNAME="TESTJSON" BORDER="thin" BORDERSTYLE="normal" CAPTION="yes"
ICON="TESTJSON/images/TEST_twit_logo_ijM_icon.ico" MAXIMIZEBUTTON="yes" MINIMIZEBUTTON="yes" SYSMENU="yes"
SCROLL="no" NAVIGABLE="yes" SINGLEINSTANCE="no" SHOWINTASKBAR="yes" VERSION="1.0" WINDOWSTATE="normal">
<script>
window.location = 'testJSON.html';
</script>
</head>
</html>
testJSON.html
<!DOCTYPE html>
<html>
<head>
<title>TEST - JSON Editor</title>
<meta http-equiv="x-ua-compatible" content="IE=edge" />
<link rel="stylesheet" href="TESTJSON/css/bootstrap.min.css">
<link rel="stylesheet" href="TESTJSON/css/style.css">
<script src="TESTJSON/js/jquery.min.js"></script>
<script src="TESTJSON/js/bootstrap.min.js"></script>
<!--Begin Vbscript-->
<script language="VBScript">
</script>
</head>
<body onload="readJSON()" scroll="no">
<div class="logo">
<img class="logo-image" src="TESTJSON/images/TEST-logo.png">
</div>
<div class="container">
<div class="row">
Select a JSON file: <input type="file" accept=".json" name="jsonFile"><br><br>
</div>
</div>
<div class="status_window">
Status / Information:
<div class="status_window_text" id="output">
</div>
</div>
</body>
<!--Begin Jscript-->
<script type="text/javascript">
function readJSON() {
$(document).ready(function () {
$.getJSON("example_2.json", function (data) {
var content = '<h3>' + data.quiz.sport.q1.question + '</h3>';
$(content).appendTo("#output");
});
});
}
function myFunction() {
alert("Page is loaded");
}
</script>
</html>
example_2.json
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
}
}
}
}
Using HTML5 FILE API I was able to get the script working with the code below
This is the query from the JSON I was able to return.
JsonObj.quiz.sport.q1.question
Code:
function readJSON() {
//Testing to see if the text would display in the DIV
document.getElementById("output").innerHTML = "Importing JSON....";
//script start
JsonObj = null
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
f = files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
JsonObj = JSON.parse(e.target.result);
console.log(JsonObj);
document.getElementById('output').innerHTML += '<ul>' + JsonObj.quiz.sport.q1.question + '</ul>';
};
})(f);
// Read in the image file as a data URL.
reader.readAsText(f);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
}
i've tried to add an object to my array savedTemplates in a service with the function getTemplates.
I've used a service for this in order to access the templates in multiple views.
Unfortunately, if i try to call my function, nothing happens.
services.js:
.factory('templateData', function(){
var savedTemplates = [
{"name":"Adam Müller", "iban":"AT29100020003000","image":"adam.jpg"},
{"name":"Ben Streicher","iban":"AT34900080007000","image":"ben.png"},
{"name":"Max Krossmann","iban":"AT23400050006000","image":"max.png"}
];
var getTemplates = function(){
return savedTemplates;
};
var addTemplates = function(insertName,insertIban){
savedTemplates.push=({"name": insertName, "iban": insertIban, "image": 'mike.png'});
alert("This is savedTemplates:" + savedTemplates);
};
return {
getTemplates:getTemplates,
addTemplates:addTemplates
};
})
template-save.html:
<button class="button button-large button-positive" ng-click="addTemplates(newreceiver,newiban)" ui-sref="tab.templates">
Speichern
</button>
I would be very grateful for any help, since I'm quite desperated already.
Here is a sample snippet.
You also have a problem in your factory addTemplates code, you should use savedTemplates.push ({ ... }], not savedTemplates.push = ({ ... }]
Snippet
angular.module('app', []);
angular.
module('app')
.controller('ExampleController', ['$scope', 'templateData', function($scope, templateData) {
$scope.addTemplates = templateData.addTemplates;
}])
.factory('templateData', function() {
var savedTemplates = [{
"name": "Adam Müller",
"iban": "AT29100020003000",
"image": "adam.jpg"
},
{
"name": "Ben Streicher",
"iban": "AT34900080007000",
"image": "ben.png"
},
{
"name": "Max Krossmann",
"iban": "AT23400050006000",
"image": "max.png"
}
];
var getTemplates = function() {
return savedTemplates;
};
var addTemplates = function(insertName, insertIban) {
savedTemplates.push ({
"name": insertName,
"iban": insertIban,
"image": 'mike.png'
});
console.log("This is savedTemplates:" + JSON.stringify(savedTemplates, null, 2));
};
return {
getTemplates: getTemplates,
addTemplates: addTemplates
};
});
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="addTemplates('Marty McFly', 'BTTF900080007000')">
Speichern
</button>
</body>
</html>
I am using ui-grid to bind data from Role Table which contains Department Id as PrimaryKey. I am calling Web Api to get all the roles in the table and show in ui-grid.
Department Table
Role Table
My real problem is that I want to convert Department Id to Department Name when it binds to grid using cellFilter and that is why I declare objMapping to map Department Id with Department Name. But every time when I run I see that cellFilter custom function i.e. 'mapDepartmentName' is getting called before objMapping is being set and also I am not able to refer objMapping in 'mapDepartmentName'.
My grid looks like this:-
However when I edit I get the result as below which is absolutely correct:-
My code snippet as below:-
var myApp = angular.module('appHome', ['ui.grid', 'ui.grid.edit']);
myApp.controller("ctrlRole", ['$scope', 'MetadataOrgFactory', function ($scope, MetadataOrgFactory) {
var arrDepts = [];
var objMapping = {};
MetadataOrgFactory.getApiCall('getpublisheddepts', function (dataSuccess) {
$scope.department = dataSuccess;
for (var cntElem = 0; cntElem < dataSuccess.length; cntElem++) {
var objDept = { id: dataSuccess[cntElem].DeptId, DeptId: dataSuccess[cntElem].DeptName }
arrDepts.push(objDept);
objMapping[dataSuccess[cntElem].DeptId] = dataSuccess[cntElem].DeptName;
}
$scope.gridRole.columnDefs[1].editDropdownOptionsArray = arrDepts;
}, function (dataError) {
});
$scope.gridRole = {
data: 'roleData',
columnDefs: [
{
field: 'RoleName', displayName: 'Role Name',
},
{
field: 'DeptId', displayName: 'Department Name',
editableCellTemplate: 'ui-grid/dropdownEditor',
cellFilter: 'mapDepartmentName:this',
editDropdownValueLabel: 'DeptId',
},
{
field: 'RoleDesc', displayName: 'About Role',
},
{
field: 'WorkingHrs', displayName: 'Working Hours',
},
{
field: 'RequestNumber', displayName: 'RequestNumber',
cellEditableCondition: true
}
]
}
MetadataOrgFactory.getApiCall('getallroles', function (dataSuccess) {
$scope.roleData = dataSuccess;
}, function (dataError) {
});
}])
.filter('mapDepartmentName', function () {
return function (input, scope) {
if (!input) {
return '';
} else {
return objMapping[input];
}
};
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.gridStyle {
border: 5px solid #d4d4d4;
height: 200px;
}
</style>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<link rel="stylesheet" href="https://cdn.rawgit.com/angular-ui/bower-ui-grid/master/ui-grid.min.css" />
<script src="https://cdn.rawgit.com/angular-ui/bower-ui-grid/master/ui-grid.min.js"></script>
<script src="../Scripts/AngularControllers/RoleController.js"></script>
<script src="../Scripts/AngularServices/ApiCallService.js"></script>
</head>
<body ng-app="appHome">
<div ng-controller="ctrlRole">
<div class="gridStyle" ui-grid="gridRole" ui-grid-edit>
</div>
</div>
</body>
</html>
Call $scope.$apply() in getpublisheddepts at the end of factory callback.
as you didnt show ur factory I believe its doing something asynchronously which is not informing the view to reflect changes.
I stuck in the issue for long time.
I did the following change in the code and I am getting the results as well. Please let me know if this is the correct solution for this:-
MetadataOrgFactory.getApiCall('getpublisheddepts', function (dataSuccess) {
$scope.department = dataSuccess;
for (var cntElem = 0; cntElem < dataSuccess.length; cntElem++) {
var objDept = { id: dataSuccess[cntElem].DeptId, DeptId: dataSuccess[cntElem].DeptName }
arrDepts.push(objDept);
objMapping[dataSuccess[cntElem].DeptId] = dataSuccess[cntElem].DeptName;
}
$scope.deptmapping = objDeptMapping; //new code added here
$scope.gridRole.columnDefs[1].editDropdownOptionsArray = arrDepts;
}, function (dataError) {
});
Filter Class
.filter('mapDepartmentName', function () {
return function (input, scope) {
if (!input) {
return '';
} else {
return scope.grid.appScope.deptmapping[input]; //Change in code
}
};
});
I am trying to make put call in angular js after selecting value from dropdown selection. I already got value from selection. Just want too make put call but not able to make response.
Here is HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.js"></script>
<script data-require="jquery#1.8.3" data-semver="1.8.3" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="sensorsCtrl">
<span class="sensors actionable u-mv" id="myid" ng- click="addSequenceLink()">
Add Sequence Link
</span>
<div ng-show="innerIsIsLoading" style="position: fixed; z-index: 999999; top: 450px; left: 65%">
<px-spinner size="50"></px-spinner>
</div>
<div>
<select ng-model="asset1" id="assetNameGroup" ng-change="changedValue(asset1)" ng-options="x.name for x in Nameitems track by x.uri">
<option>Select Name</option>
</select>
<select ng-model="asset2" id="assetNameGroup2" ng-change="sectionChangedValue(asset2)" ng-options="x.name for x in asset1.sections">
<option value="">Select Name</option>
</select>
<select ng-model="asset3" id="assetNameGroup3" ng-change="positionChangedValue(asset3)" ng-options=" x.sensorPositionName for x in asset2.ultrasonicSensorPositions">
<option value="">Select Name</option>
</select>
{{positionItem}}
</div>
</body>
</html>
javascript
console.clear();
var app = angular.module("myApp", []);
app.controller('sensorsCtrl', function($scope, $window, $timeout, $http{
$scope.innerIsIsLoading = true;
$http.get('sample.json').success(function(resp) {
$scope.innerIsIsLoading = false;
$scope.assetData = resp;
$scope.Nameitems = [];
var testobj = $scope.assetData[0].name;
angular.forEach($scope.assetData, function(val, key) {
$scope.Nameitems.push({
"name": val.name,
"uri": val.uri,
"sections": val.sections
});
});
});
$scope.itemList= [];
$scope.sectionItem = [];
$scope.positionItem = [];
$scope.changedValue = function(item){
$scope.itemList.push(item.sections);
}
$scope.sectionChangedValue = function(item){
$scope.sectionItem.push(item.ultrasonicSensorPositions)
}
$scope.positionChangedValue = function(item){
$scope.positionItem.push(item)
}
$scope.onclick= function(currentUlSensor){
var req = {
method: 'PUT',
url: xyz,
headers: {
'Content-Type': 'application/json'
},
data: $scope.positionItem;
}
$http(req).success(function (response) {
$scope.isLoading = false;
$scope.xyz= response;
});
}
});
Data should be from last drop down section data make put call and request data is like this
[
{
"ultrasonicSensorPositionId": 18,
"sensorPositionName": "ultrasonic sensor position 1",
"diameter": 22.5,
"rotation": 90,
"sequenceNumber": 1,
"sectionId": "/assets/332008d3-fddc-391b-9cc1-6a41f7ff73d1"
},
{
"ultrasonicSensorPositionId": 19,
"sensorPositionName": "ultrasonic sensor position 2”,
"diameter": 22.5,
"rotation": 90,
"sequenceNumber": 2,
"sectionId": "/assets/332008d3-fddc-391b-9cc1-6a41f7ff73d1"
}
]
here is plunker demo .
Your request seems to be OK - just remove the ; from data: $scope.positionItem;. I usually use:
$http({
url: xyz,
method: 'PUT',
contentType: 'application/json; charset=utf-8',
data: $scope.positionItem
}).then(function (result) { // this is the success
...
}, function (error) { // this is the error
....
});