can't select specific elements from data contained in <?!=JSON.stringify(dataFromServerTemplate) ?> - javascript

I have a problem with JSON format. I'm new at this kind of stuff so I can't figure out which is the problem. In google app script I have this get function
function doGet() {
var htmlTemplate = HtmlService.createTemplateFromFile('html');
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1_cj_HO2oN6CYe_Pb7Cy8S3yVtwKW8Efr-Sdyf1Sk8Ts/edit#gid=2009573145");
htmlTemplate.dataFromServerTemplate = makeJSON(getRowsData_(ss.getSheetByName("Foglio8"),getExportOptions()),getExportOptions());
var htmlOutput = htmlTemplate.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('sample');
return htmlOutput;
}
Now, here is the part of the HTML which isn't working
<div>
<p id="tx"></p>
</div>
<script type="text/javascript">
var data = <?!=JSON.stringify(dataFromServerTemplate) ?>;
function caric(){
document.getElementById("tx").innerText= data.saldo;}
</script>
</body>
Function caric() runs onload of the page. "saldo" is actually contained in this JSON.
If I use data.saldoI receives undefined but if I only use data it works and prints everything that is contained in the JSON.
Do you know what I'm doing wrong?
Thanks

JSON.stringify produces a string not an object. In your server code you should do something like this.
var obj = { name: "me", gender: "male", eyes: "blue" };
htmlTemplate.dataFromServerTemplate = JSON.stringify(obj);
And on the client side this
var data = JSON.parse(<?= dataFromServerTemplate ?>);
(function caric(){
document.getElementById("tx").innerText= data.name;}());

Related

JavaScript script won't load contents of a JSON file to process

I am trying to load a JSON file into a JavaScript script for use in a Mustache script on a webpage. The JSON in a string loads correctly, but the same JSON in a file does not.
This works:
function renderHello() {
var json = JSON.parse('{"cloudy": "This applies to Snowflake.","classic": "This applies to SQL Server."}');
var template = document.getElementById("template").innerHTML;
var rendered = Mustache.render(template, json);
document.getElementById("target").innerHTML = rendered;
}
This does not work:
function renderHello() {
var json = JSON.parse('./abc.json');
var template = document.getElementById("template").innerHTML;
var rendered = Mustache.render(template, json);
document.getElementById("target").innerHTML = rendered;
}
Variations I've tried in abc.json:
{
"cloudy": "This applies to Snowflake.",
"classic": "This applies to SQL Server."
}
{"cloudy": "This applies to Snowflake.","classic": "This applies to SQL Server."}
I've unsuccessfully tried
var json = './abc.json';
var json = JSON.parse('./abc.json');
var json = JSON.stringify('./abc.json');
var json = JSON.parse(JSON.parse('./abc.json'));
var json = JSON.parse(JSON.stringify('./abc.json'));
Frequently an error like this is returned in the Chrome Developer Tools:
VM223:1 Uncaught SyntaxError: Unexpected token . in JSON at position 0
at JSON.parse (<anonymous>)
at renderHello (render.js:2)
at onload (docs.html:91)
I added these lines in the script to reveal the location of the website file that includes the Mustache template, so I knew where to locate abc.json:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(dir)
And the file structure is now this:
directory
--file-with-mustache-script.html
--abc.json
This may not be relevant, but this is the Mustache script, which of course already works with the JSON as a string.
<body onload="renderHello()">
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
Hello {{ cloudy }}, {{ classic }}!
</script>
</body>
The website build tool I'm using does not support Node or Handlebars.
If it is relevant at all, the goal is to populate values from a JSON file in a product documentation website page to indicate which paragraphs apply to which product version.
You need to load the content of the file via "AJAX". You can't get the content like you are trying to do.
Something like this would do the job:
function renderHello() {
fetch('https://jsonplaceholder.typicode.com/users/3').then(r=>r.json())
.then(json=>{
// var template = document.getElementById("template").innerHTML;
// var rendered = Mustache.render(template, json);
document.getElementById("target").innerHTML = JSON.stringify(json,null,2);
})
}
renderHello();
<pre id="target"></pre>
As I don't have access to your abc.json file I used a publicly resource at http://typicode.com.

Calling a second javascript function that is located in a different file

I have created a HTML form within the google apps script environment. With two files one HTML file including the HTML form and the relevant CSS, and another form including my java script functions.
When the submit button is pressed it calls a function GetSelectedText(), which returns the selected text value of a selection input. This function is within the HTML page.
What I then want to happen is once the GetSelectedText() function is called to call another function projectData() passing over the collected input value from the GetSelectedText().
However it doesn't pass over the variable and in the log it just has 'null'.
Any help on this would be greatly appreciated. Thanks.
<script>
function GetSelectedText(){
var e = document.getElementById("projectNoView");
var result = e.options[e.selectedIndex].text;
projectData(result);
}
</script>
function projectData(result) {
var ss = SpreadsheetApp.openById('10jSs0uoHOgO9VZusCa0ApyXmqISsHqsubIfRXiRPcQg');
var sheet = ss.getSheetByName("Projects Progress");
var data = sheet.getDataRange().getValues();
var search = result;
var optionsHTML = "";
var NICEIC = "0";
Logger.log(search);
for(var i = 0; i<data.length;i++){
if(data[i][0] == search){
var NICEIC = sheet.getRange((i+1), 3).getDisplayValue();
optionsHTML += '<input id = "mytext" name = "NICEIC" type = "text" placeholder="NICEIC" value="' + NICEIC + '" tabindex="2">'
}
};
return optionsHTML;
}
Server side functions can't be called directly from the client side code, you have to use google.script.run to do that. Example from the Google Apps Script guides
Server side code (Code.gs)
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function doSomething() {
Logger.log('I was called!');
}
Client side code (Index.html)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
google.script.run.doSomething();
</script>
</head>
</html>
Reference
HTML Service: Communicate with Server Functions

Reading array from java servlet in javascript

Hi like the title says I am trying to read an array from my java Servlet. I am trying to read the array in my java script file.
Java servlet code:
String graphData[] = dbHandler.select(attributes); // filling the array with data from database.
request.setAttribute("graphData", graphData);
RequestDispatcher dispatcher = request.getRequestDispatcher("/displayData.jsp");
dispatcher.forward(request, response);
<script type="text/javascript">
var graphData = ['${graphData}'];
var graphData= pageContext.getAttribute("graphData");
var graphData = document.getElementById("graphData");
var GraphData = ['${graphData}'];
log("test: " + graphData);
</script>
I tried all those options but none of them worked.
Can someone please tell me what the correct way is to read an array from a java servlet in a jsp page?
Thanks in advance!
edit:
what I can do is print out the data from the array on the JSP page (in the header) with this code:
<c:forEach items="${graphData}" var="temp">
<c:out value="${temp}"/><br />
</c:forEach>
But I want to use the data from the array in my JS code. which for some reason doesn't work.
You can use like this
<script>
var graphData = [
<c:forEach items="${graphData}" var="graph">
'<c:out value="${graph}" />',
</c:forEach>
];
console.log(graphData);
</script>

Mustache.to_html() returning an empty string

This question was asked before but didn't get an answer. I have a php file which sends a json object to a javascript file which is supposed to render it with a template and display it on a div. The problem is, the function Mustache.to_html() returns empty. can anyone tell me what I am doing wrong. here's my code.
{
$(":button").click(function(){
var cat = $(this).attr("name");
$.get("trier.php",{input: cat}, function(data){
alert(data);
var template = $('#templabel').html();
console.log(template);
var html = Mustache.to_html(template, data);
console.log(html);
$('#feedback2').html(data);
});
});
}
The javascript sends the data to this php file which sends back a json object
{
if(isset($_GET['input'])){
$catt = $_GET['input'];
$info = "SELECT * FROM books WHERE (Category = '$catt')";
$information = mysqli_query($conn,$info);
$arraay = array();
while($r = mysqli_fetch_assoc($information)){
$arraay[] = $r;
}
$jason = json_encode($arraay);
$jason = '{"arraay":'.$jason."}";
echo $jason;
}
}
The javascript file will then send the json object rendered with the mustache template to the html file, to the tag with the id = "feedback2". But the display is raw json, not templated. and the second console.log after I apply the Mustache.to_html function returns an empty string. What am I doing wrong?
The output of the console.log for the template is
{{#arraay}}
<div>
<h2> {{Title}}</h2>
<p>{{Course}}</p>
<p>{{Category}}</p>
</div>
{{/arraay}}
and the alert for the data is
{"arraay":[{"Title":"Algorithms","Course":"CSI241","Category":"science"},{"Title":"Fluid dynamics","Course":"PHY345","Category":"science"}]}
Works for me:
var data = {"arraay":[{"Title":"Algorithms","Course":"CSI241","Category":"science"},{"Title":"Fluid dynamics","Course":"PHY345","Category":"science"}]};
var template = document.getElementById('template').innerHTML;
var html = Mustache.to_html(template, data);
document.getElementById('render').innerHTML = html;
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.2.0/mustache.min.js"></script>
<template id="template">
{{#arraay}}
<div>
<h2> {{Title}}</h2>
<p>{{Course}}</p>
<p>{{Category}}</p>
</div>
{{/arraay}}
</template>
<div id="render">
</div>

accessing a javascript variable in handlebars template

I am getting a php varible in javascript as
window.apiUserId = '<?php echo Yii::$app->user->id ?>';
And I have a handlebar template as
<script type="text/x-handlebars">
{{log apiUserId}}
{{outlet}}
</script>
But the console displays "undefined"
How to log javascript variables in handlebars ?
From the documentation:
var context = {title: "My New Post", body: "This is my first post!"}
var html = template(context);
Therefore:
var context = {apiUserId: window.apiUserId};
var html = template(context);
I suppose you might manage to make:
var html = template(window);
… work, but splurging that much arbitrary data into the function is a good recipe for unexpected results.

Categories