How do you run scripts off of handlebar data - javascript

I'm trying to parse data from a node.js/ express server which I wish to use on the client-side as a variable (although I understand this could most likely all be done server-side, I'm trying to learn about how handlebars handles data). At this stage I wish to have it as an object I can print so I can use it at a later stage. My current code is as follows:
Handler for request
exports.getList = (req,res) => {
console.log("Request for list sent");
var MyDataObject = {
days: 75,
people: 12
};
return res.status(200).render("home", {MyDataObject});
};
Client-Side
<script>
handleServerData = (ServerDataObject) => {
console.log(ServerDataObject);
};
</script>
{{#if MyDataObject}}
<script>handleServerData({{MyDataObject}})</script>
{{/if}}
When the page is requested through the shown handler this simply gives the error Uncaught SyntaxError: Unexpected identifier Which I assume is from it setting {{MyDataObject}} to [object Object] inside the sources view however I don't know how to fix this although I assume it does it because of it running the script before the handlebars parse the data.
Any help fixing this is greatly appreciated.

Related

How to set ejs data to data atribute and parse it in client side js?

I am trying to send leaderboard data from the server to the client side javaScript. Heres my server side javascript.
const leaderboard = [[dog,cat],[car,bus],[foo,bar]]
const toJson = JSON.stringify(leaderboard)
res.render('games/dodge.ejs', {
leaderboard: toJson
})
Here is how my ejs file recives it
<div data-leaderboard="<%= leaderboard%>"></div>
and then there is the clientside js dodge_leaderboards.js
const leaderboardData = document.querySelector("[data-leaderboard]")
console.log(leaderboardData)
When I run this code it returns an error that says Uncaught SyntaxError: Identifier 'leaderboardData' has already been declared (at dodge_leaderboards.js:1:1)
Also the console.log returns null.
I am trying to assing the arrays inside the big array to own variables, but now I am having problems with just a simple console.log. What do you think is causing the problem, I am also curios to hear how to parse the array.
Okay I got it working I forget to put ".dataset.leaderboard" after the leaderboardData
const leaderboardData = document.querySelector("[data-leaderboard]")
console.log(leaderboardData.dataset.leaderboard)

Ajax Error : Uncaught SyntaxError: Unexpected token '<' [duplicate]

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:
{"votes":47,"totalvotes":90}
I don't see any problems with it, why would this error occur?
vote.each(function(e){
e.set('send', {
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = JSON.decode(resp);
if (!j) return false;
var restaurant = e.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
});
e.addEvent('submit', function(e){
e.stop();
this.send();
});
});
Seeing red errors
Uncaught SyntaxError: Unexpected token <
in your Chrome developer's console tab is an indication of HTML in the response body.
What you're actually seeing is your browser's reaction to the unexpected top line <!DOCTYPE html> from the server.
Just an FYI for people who might have the same problem -- I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:
vote.each(function(element){
element.addEvent('submit', function(e){
e.stop();
new Request.JSON({
url : e.target.action,
onRequest : function(){
spinner.show();
},
onComplete : function(){
spinner.hide();
},
onSuccess : function(resp){
var j = resp;
if (!j) return false;
var restaurant = element.getParent('.restaurant');
restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
$$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
buildRestaurantGraphs();
}
}).send(this);
});
});
If anyone knows why the standard Request object was giving me problems I would love to know.
I thought I'd add my issue and resolution to the list.
I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:
var total = $.parseJSON(response);
I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.
I found that out by just doing a console.log(response) in order to see what was actually being sent. If it's an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.
When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).
According to MooTools docs:
Responses with javascript content-type will be evaluated automatically.
In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:
{"votes":47,"totalvotes":90}
as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following "code":
"votes":47,"totalvotes":90
As you can see, : is totally unexpected there.
The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.
It sounds like your response is being evaluated somehow. This gives the same error in Chrome:
var resp = '{"votes":47,"totalvotes":90}';
eval(resp);
This is due to the braces '{...}' being interpreted by javascript as a code block and not an object literal as one might expect.
I would look at the JSON.decode() function and see if there is an eval in there.
Similar issue here:
Eval() = Unexpected token : error
This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.
Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.
If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below
<br />
<b>Deprecated</b>: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:\Projects\rwp\demo\en\super\ge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}
Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start
error_reporting(E_ERROR | E_PARSE);
To view, right click on page, "view source" and then examine complete html to spot this error.
"Uncaught SyntaxError: Unexpected token" error appearance when your data return wrong json format, in some case, you don't know you got wrong json format.
please check it with alert(); function
onSuccess : function(resp){
alert(resp);
}
your message received should be: {"firstName":"John", "lastName":"Doe"}
and then you can use code below
onSuccess : function(resp){
var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp);
}
with out error "Uncaught SyntaxError: Unexpected token"
but if you get wrong json format
ex:
...{"firstName":"John", "lastName":"Doe"}
or
Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}
so that you got wrong json format, please fix it before you JSON.decode or JSON.parse
This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.
So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get
Uncaught SyntaxError: Unexpected token <
So to help find the offending path/request look for 302 requests.
Hope that helps someone.
I had the same problem and it turned out that the Json returned from the server
wasn't valid Json-P. If you don't use the call as a crossdomain call use regular Json.
My mistake was forgetting single/double quotation around url in javascript:
so wrong code was:
window.location = https://google.com;
and correct code:
window.location = "https://google.com";
In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.
I got this error because I was missing the type attribute in script tag.
Initially I was using but when I added the type attribute inside the script tag then my issue is resolved
I got a "SyntaxError: Unexpected token I" when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.
In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller
#RequestMapping(name="/private/updatestatus")
i changed the above mapping to
#RequestMapping("/private/updatestatus")
or
#RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)
For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You'll immediately see the red circle with a cross in it on the failing line. It's a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.
I did Wrong in this
`var fs = require('fs');
var fs.writeFileSync(file, configJSON);`
Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error...
For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn't be found. I just had to provide a reachable path and the problem went away.
In my case it was a mistaken url (not existing), so maybe your 'send' in second line should be other...
This error might also mean a missing colon or : in your code.
Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock
xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'\n at eval (<anonymous>)\n at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.
Try this to ignore this issue:
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
Uncaught SyntaxError: Unexpected token }
Chrome gaved me the error for this sample code:
<div class="file-square" onclick="window.location = " ?dir=zzz">
<div class="square-icon"></div>
<div class="square-text">zzz</div>
</div>
and solved it fixing the onclick to be like
... onclick="window.location = '?dir=zzz'" ...
But the error has nothing to do with the problem..

How to fix frontend javascript in handlebars catching undefined value from server?

I have a JSON object in backend which I want to send to frontend javascript. But I'm constantly encountering "undefined" when trying to access that variable.
candidates is json object and is working fine in server side.
Here's my server side code.
res.render('electionview',{title: 'Election', poll: poll, data: JSON.stringify(candidates) });
Here's my script in Handlebars
<script type="text/javascript">
var candidates = {{{data}}};
console.log(candidates);
<script>
But I'm getting this error in console.
Uncaught SyntaxError: Unexpected token ';'
When I remove semicolon, output in the console is undefined. What am I missing ?
Server-side:
let obj = {};
obj.title = 'Election';
obj.poll = poll;
obj.data = candidates;
res.render('electionview', obj);
I'm assuming that the render function already knows how to serve objects as JSON, so no need to JSON.stringify anything.
Then, on the client-side, JSON.parse() the object above in whole. After that, it should have a data property that you can use as needed.
I was getting candidates as:
Candidate.find({}).lean()
.then(candidates=>res.render("electionview", JSON.stringify(candidates))
Removing .lean() fixed it.

Can't Render EJS Template on Client

I'm coding an application on express, and I'm using ejs as a view/template engine.
At path /artists, I'm rendering the view artists.ejs which has artists covers. When clicking on a cover, I want an AJAX call to retrieve the corresponding data, place it in my template/view for artist artist.ejs and display this template in my HTML under the cover.
I've seen this related question but it has not solved my use case.
Everything seems clear, but I can't render the data with the template. I would like to compile the template server-side, send it to the client ready to use, and then fill it in when needed with the data received from the AJAX call.
What I've done:
When calling /artists, compile on server-side using ejs.compile(str, opt):
router.get('/artists', function(req, res) {
// Compile artist template
fs.readFile('views/artist.ejs', "utf-8", function(err, template) { // Convert template file to string
artist_template = ejs.compile(template); // Compile template
res.render('artists.ejs', {template: artist_template}); // render page with compiled template
});
I took care of converting the file into String, as ejs compiler only works with String (compared to Jade .compileFile)
Then on client-side, I grab the function:
<script>
var template = <%= template %>
</script>
Then on another script, I retrieve the data with an AJAX call:
$.get('/artists/'+artist_name, function(data) {
var html = template({artist: data});
$('#artist-page').html(html);
}
But when I make the call, I receive:
Uncaught ReferenceError: fn is not defined
When I call the template, fn, I receive:
Uncaught ReferenceError: opts is not defined.
Is the function fn hard-coded? I've read the EJS and Jade documentation but there was little relevant information in regards to my issue.
Do I perhaps need the template on client-side also?
I eventually found a workaround to my question, and I understood with your answer that you could proceed in 2 different ways:
1) What I did: read and save template as a string, then render it client-side with ejs Runtime script.
// In controller.js
var templates = {};
templates.template1 = fs.readFileSync(filePath1, 'utf-8'); // Read template as a string
templates.template2 = fs.readFileSync(filePath2, 'utf-8');
...
res.render('app.ejs', {templates: templates}); // Send templates in view
// In view app.ejs
<script type="text/javascript">
var templates = <%- JSON.stringify(templates) %>; // Get templates object (object of strings)
</script>
<script type="text/javascript" src="/JS/ejs.min.js"></script> <!-- Load ejs RunTime -->
// In site.js - javascript client/public file
$.get('/artists', function(data) {
var html = ejs.render(templates.template1, data); // Render ejs client side with EJS script (template1 corresponds to the artists template)
$('#artists-wrapper').html(html); // Sets HTML
});
Thus, I send all my templates on first page load, and then I render the requested page on the client side. The interest, according to what I've read, is that you only send JSON object (your data) through AJAX calls, and not the entire page, making your request light. Only the first load is heavy with all your templates.
2) What I would like to do according to #RyanZim answer: compiling templates server side into functions, send them, and then call them on the client side : template(data). If I understood well, there is no need of EJS client library in this case, and my templates are no longer strings but functions:
// In controller.js
var templates = {};
templates.template1 = ejs.compile(fs.readFileSync(filePath1, 'utf-8'), {client: true}); // Get template as a function
templates.template2 = ejs.compile(fs.readFileSync(filePath2, 'utf-8'), {client: true});
...
res.render('app.ejs', {templates: templates}); // Send templates in view
However, I can't get them in my view:
<script type="text/javascript">
var templates = <%- JSON.stringify(templates) %>; // Get templates object (object of functions)
</script>
is not working. they are functions on the server before I send them, but I don't know how to recover them. Do you have an idea ?
I tried a workaround, by changing them into String before sending them:
templates.template1 = templates.template1.toString();
Send them and then client side, transform them back in functions:
var template = new Function(templates.template1);
$.get('/artists', function(data) {
var html = template(data);
$('#artists-wrapper').html(html); // Sets HTML
});
But that won't work either.
Do you have an idea what I'm missing here?
And last, do you agree that compiling them server side before using the functions is better in terms of computation than rendering each template client-side?
Thanks for the help, and hope that will help anybody else!
You need to use the client option on the server side when you are compiling for the client. From the docs:
client When true, compiles a function that can be rendered
in the browser without needing to load the EJS Runtime
https://github.com/mde/ejs#options
Your server-side code snippet should be:
// Compile artist template
fs.readFile('views/artist.ejs', "utf-8", function(err, template) {
artist_template = ejs.compile(template, {client: true}); // Use client option
res.render('artists.ejs', {template: artist_template});
});

JQuery Unable to get property 'json' of undefined or null reference

Im building a windows 8 app (html)
And have a api im fetching data from.
I keep getting this error however
0x800a138f - JavaScript runtime error: Unable to get property 'json' of undefined or null reference
in my scripts1.js file. then my program crashes -_-.
Here is the the code i use
$(function () {
startRefresh();
});
function startRefresh() {
setTimeout(startRefresh, 10000);
var url = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132';
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=json', function (data) {
jQuery('#ticker').html(data['query'].results.json.return.markets.DOGE.lasttradeprice);
jQuery('#ticker').append(' ' + data['query'].results.json.return.markets.DOGE.secondarycode);
jQuery('#ticker2').html(data['query'].results.json.return.markets.DOGE.lasttradetime);
jQuery('#ticker3').html(data['query'].results.json.return.markets.DOGE.volume);
});
}
This is located in scripts1.js Then i use ect.
It works everything comes and displays just get that error. Not sure what to do.
Seems like data['query'].results is undefined. Pasting the JSON you get will help.
Also, one small piece of advice: If you are going to access an in-depth attribute and, specially, a DOM node several times, you might want to recycle a reference to it rather than travelling again and again to fetch it for performance reasons. Something like this:
var ticker = jQuery('#ticker');
var DOGE = data['query'].results.json.return.markets.DOGE;
ticker.html(DOGE.lasttradeprice);
...
It looks like, occasionally, the API will send back some JSON that, when parsed, doesn't contain a results object. To mitigate this you should put a condition in to catch this eventuality.
if (data.query.results) {
jQuery('#ticker').html(data['query'].results.json.return.markets.DOGE.lasttradeprice);
// rest of DOM update code
}
Demo.

Categories