handlebars and JSON data coming from a fetch - javascript

I have the code below and have 2 separate issues, so please bear with me on this:
Issue 1 [fetch ?]:
The data displayed doesn't change when the JSON change. Sounds like it's a cache issue as I can't see any HTTP request beside the original one. How can I force the JSON file to be downloaded again each time?
Issue 2 [handlebars ?]: with $(document.body).append(html); in the loop, it keeps re-writing the instead of editing the values. How can I change this?
Here is the code:
javascript.js:
async function fetch_json() {
try {
var resp = await fetch('http://localhost:8000/data.json', {mode: 'cors'});
var jsonObj = await jsonify(resp);
return jsonObj;
} catch (error) {
// all errors will be captured here for anything in the try block
console.log('Request failed', error);
}
}
html page:
<script id="handlebars-demo" type="text/x-handlebars-template">
<div>
{{#each this}}
Name : {{name}} Value : {{value}} <br>
{{/each}}
</div>
</script>
<script type="text/javascript">
var test_data = [{ "name" : "john doe", "value" : "developer" },{ "name" : "bob boby", "value" : "developer2" }];
setInterval(function() {
test_data = fetch_json()
.then(function(result) {
html = templateScript(result);
//$(document.body).append(html);
})
}, 1000);
var template = document.getElementById('handlebars-demo').innerHTML;
Compile the template data into a function
var templateScript = Handlebars.compile(template);
var html = templateScript(test_data);
$(document.body).append(html);
</script>
any help would be the most appreciated, thank you!

You should create a DOM element to hold the HTML you are generating. I've created <div id="content"></div> in the example.
You can use $().html() to overwrite the HTML each time instead of appending.
$('#content') selects the DOM element with id=content and then overwrite the HTML inside .html(string) with string.
A common approch to cache busting is to attach a timestamp to the url as a url query param, which I have done by concatenating nocache='+new Date().getTime().
In normal use in production a unique identifier is usually generated per version for each resource after building.
// for demo purposes, overwrite value property with username property
jsonify = x => x.json().then(x => x.map(x => ({ ...x,
value: x.username
})));
async function fetch_json() {
try {
// append timestamp to prevent caching
var resp = await fetch('https://jsonplaceholder.typicode.com/users?nocache=' + new Date().getTime(), {
mode: 'cors'
});
var jsonObj = await jsonify(resp);
return jsonObj;
} catch (error) {
// all errors will be captured here for anything in the try block
console.log('Request failed', error);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.js" integrity="sha256-ZafrO8ZXERYO794Tx1hPaAcdcXNZUNmXufXOSe0Hxj8=" crossorigin="anonymous"></script>
<div id="content"></div>
<script id="handlebars-demo" type="text/x-handlebars-template">
<div>
{{#each this}} Name : {{name}} Value : {{value}} <br> {{/each}}
</div>
</script>
<script type="text/javascript">
var test_data = [{
"name": "john doe",
"value": "developer"
}, {
"name": "bob boby",
"value": "developer2"
}];
setInterval(function() {
test_data = fetch_json()
.then(function(result) {
html = templateScript(result);
$('#content').html(html);
})
}, 2000);
var template = document.getElementById('handlebars-demo').innerHTML;
//Compile the template data into a function
var templateScript = Handlebars.compile(template);
var html = templateScript(test_data);
$('#content').html(html);
</script>

Related

getting a specific value from JSON.parse() javascript

Hello I am trying to figure out how to get the "changes" value from
{ data: { sequenceStart: 1613141716565, symbol: 'KCS-BTC', changes: { asks: [Array], bids: [] }, sequenceEnd: 1613141716565 }, subject: 'trade.l2update', topic: '/market/level2:KCS-BTC', type: 'message' }
The data is stored in let data = JSON.parse(msg)
I have tried console.log(data.data.changes) but get undefined, im lost because console.log(data.data) seems to get me part way there but not when I add .changes?
Can you check my code below.
I think your msg is not formated correctly , you can compare with my code
<body >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
var msg = '{"data": { "sequenceStart": "1613141716565", "symbol": "KCS-BTC", "changes": { "asks":[["0","0","1613141798456"]],"bids":[]}, "sequenceEnd": 1613141716565 }, "subject": "trade.l2update", "topic": "/market/level2:KCS-BTC", "type": "message" }';
var data = JSON.parse(msg);
console.log(data.data.changes);
var msg1 = '{"sequenceStart":1613141798456,"symbol":"KCS-BTC","changes":{"asks":[["0","0","1613141798456"]],"bids":[]},"sequenceEnd":1613141798456}';
var data1 = JSON.parse(msg1);
console.log(data1.changes);
});
</script>
</body>

Ajax result change Jade assignment variable

Looking to change a Jade assigned variable with the results of an ajax post so that the page's Jade loop utilizes the new data (updating only the parts of the dom that relate to the loop and not rendering the page over).
route.js
router.post('/initial', function(req, res) {
res.render('/page', {data: data})
})
router.post('/refresh', function(req, res) {
res.send(newdata)
})
index.jade
block content
- var fluxdata = data
each item in fluxdata
span= item
div#button
client.js
$(document).on('click', '#button', function() {
$.post('/refresh', function(newdata) {
var fluxdata = newdata
})
}
I tried out partials, but wasn't sure I was on the right track. Looked around the internet and stackoverflow for a while and can't find a similar question about Jade assignments.
// Jade template
block content
div(class="content")
- var fluxdata = data
each item in fluxdata
span #{item.id} : #{item.username}
div
button(id="add") POST Data
after your template is rendered your html will look like this
// HTML rendered
<div class="content">
<span>1 : Yves</span>
<span>2 : Jason</span>
</div>
<div>
<button id="add">POST DATA</button>
</div>
// backend code
var users = [
{
username: "Yves",
id: 1
},
{
username: "Jason",
id: 2
}
]
router.get("/initial", function(request, responser) {
response.render("index", { data: users})
})
router.post("/refresh", function(request, responser) {
users.push({username: "Alex",id: 1})
response.json({ data: users})
})
// Your jquery code
$("#button").on('click', function(event){
event.preventDefault()
$.post('/refesh', function(data) {
$(".content").html("")
for(var user in data) {
var span = $("<span>")
span.text(user.id + ": " + user.username )
$(".content").append(span)
}
});
})
in your get "/initial" route handler, your are rendering the
res.render("/page", {data : data })
before the template name you musn't put the / and the template in witch you are trying to use data that at push to the view is index.jade
router.post('/initial', function(req, res) {
res.render('index', {data: data})
})

array1.filter is not a function ng-tags-input

i'm using the auto-complete in tags-input but when i start writing i get this error: array1.filter is not a function. This is my angular call
$scope.loadTags = function(query) {
var searchPeople = $scope.baseUrl + "&searchString=";
return $http.get(searchPeople + query, {
}).success(function (data) {
$scope.people = data.data.data;
console.log($scope.people);
}).error(function (data){
console.log("Error");
});
};
moreover i don't know how to retrieve a value from, in my case $scope.people json that is something like:
{
"id": 17,
"cod": "gg117",
"name": "Alex"
}
i know that i need a custom template but as long as i get the error i can't do it. By the way the template is this one but i don't know if it's correct
<script type="text/ng-template" id="my-custom-template">
<div class="left-panel">
<img ng-src="./img/avatar.jpeg" />
</div>
<div class="right-panel">
<span ng-bind-html="$highlight($getDisplayText())"></span>
<span>({{people.name}})</span>
</div>
</script>
you need to pass a promise, with data of the format
{
"data":[{'text':'tag1'}, {'text', 'tag1'}]
}

Python Django: Pass json from view to javascript in template

I am new to django.
From my findings, I tried this way, but didn't work.
<script type="text/javascript" >
var data = {{json}}
</script>
I am trying to use data table from this website, http://www.datatables.net/manual/data.
<script type="text/javascript" class="init">
var temp = '{{campaignList|escapejs}}'; // should be a list, but becomes a string
alert(typeof temp)
$(document).ready( function () {
$('#campaigns').DataTable({
data: temp,
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'date' },
]
});
} );
</script>
When I check the type before passing into datatable, the type becomes string.
I also tried {{campaignList|escapejs}} without quote, but didn't work.
Any suggestion? Thanks.
If campaignList is a json string, pass it to safe filter to prevent escape:
var data = {{ campaignList|safe }};

Syntax Error in Json while fetching in backbone.js

I am trying to fetch the data from the JSON, and trying to display it. While fetching the json, it is throwing error in fetch. I am stuck at this point from so many days, and after reading from google, I am confused. Can anyone please help me out what is the error and how to proceed.
<!DOCTYPE html>
<html>
<head>
<title>Fortified Studio</title>
</head>
<body>test
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="name">
<%= name %>
</div>
</div>
</div>
</script>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script>
$(function() {
console.log("start of script");
var Prof = Backbone.Model.extend({});
var ProfList= Backbone.Collection.extend ({
model: Prof,
url : '/data/testjson2.json'
});
var ProfView = Backbone.View.extend ({
initialize: function (){
console.log("View initialize");
this.render();
},
render : function (){
console.log("in render");
template: _.template($('#profileTemplate').html()),
_.each (this.collection, function(Prof) {
var profileTemplate = this.template(Prof.toJSON());
$(this.el).append(profileTemplate);
}, this);
console.log (this);
return this;
}
});
var profs = new ProfList ();
var profViews = new ProfView ();
new ProfList().fetch({
sucess : function(){
console.log('json loaded');
},
error: function (){
console.log("error retrieving model");
}
});
profViews.render();
});
</script>
</html>
and my JSON is:-
[
{
"name": "Johny Johny",
},
{
"name": "Jack n Jill",
}
]
and output on console is:-
.......
Unknown property 'box-sizing'. Declaration dropped. myFile.html
"start of script" myFile.html:27
"View initialize" myFile.html:37
"in render" myFile.html:41
[object Object] myFile.html:47
"in render" myFile.html:41
[object Object] myFile.html:47
GET /data/testjson2.json [HTTP/1.1 200 OK 3ms]
syntax error testjson2.json:1
"error retrieving model" myFile.html:62
Please help me out, how to proceed.
Remove the commas at the end of each value set.
[
{
"name":"Johny Johny"
},
{
"name":"Jack n Jill"
}
]
Test your JSON with:
http://jsonformatter.curiousconcept.com/

Categories