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>
Related
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.
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;}());
I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo
These are my Json arrays:
{"0":"1","id":"1","1":"2015-01-11 12:30:45","DateTimeCreated":"2015-01-11 12:30:45","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"benjiwjh","username":"benjiwjh"}
{"0":"4","id":"4","1":"2015-02-11 09:09:09","DateTimeCreated":"2015-02-11 09:09:09","2":"Pending Confirmation","status_desc":"Pending Confirmation","3":"LSH","username":"LSH"}
{"0":"7","id":"7","1":"2015-12-03 18:30:00","DateTimeCreated":"2015-12-03 18:30:00","2":"Unresolved","status_desc":"Unresolved","3":"SWJH","username":"SWJH"}
{"0":"12","id":"12","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"benjiwjh","username":"benjiwjh"}
{"0":"14","id":"14","1":"2014-12-03 12:10:30","DateTimeCreated":"2014-12-03 12:10:30","2":"Resolved","status_desc":"Resolved","3":"CYJM","username":"CYJM"}
How am I supposed to use these to display my code in an HTML file?
I have a function to show the data but it does not work:
function showData(response) {
var data = JSON.parse(response);
var id = data.id;
var DateTimeCreated = data.DateTimeCreated;
var status_desc = data.status_desc;
var username = data.username;
myText.textContent= id + DateTimeCreated + status_desc + username;
}
I think you should have a div tag in your html template.
For example, in your HTML template, there should be a scope of codes:
<div id="sometext">
</div>
And in your JS script,
var textContent = id + DateTimeCreated + status_desc + username
sometext = document.getElementById("sometext");
sometext.innerHTML(textContent);
For more info, please visit http://www.w3schools.com/js/js_output.asp
Hope it would be helpful
Based on the question, I'm not entirely sure when you are using the showData function. However, here's a jsfiddle that shows that it works: https://jsfiddle.net/qyy2nvtz/1/
<p id='hello'></p>
var myText = document.getElementById('hello');
You need to get an element before you can display something in it. So, I've initialized 'myText' with a paragraph element with id 'hello'.
Additionally, make sure that the response that is being passed in to showData is a string before you parse it. If it's already an object, then it won't be parsed.
Here you have an example, you need a div element to refer like "js":
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="js">
</div>
</body>
<script type="text/javascript">
var myText= document.getElementById("js");
var data = JSON.parse(response);
var id = data.id;
var DateTimeCreated = data.DateTimeCreated;
var status_desc = data.status_desc;
var username = data.username;
myText.textContent = id + DateTimeCreated + status_desc +username;
</script>
</html>
Further reading: http://www.w3schools.com/dom/prop_element_textcontent.asp
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.