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.
Related
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)
I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?
Based on your screenshot it looks like the body data is a JSON string. That means you have to parse it first before you can use it. Something like this:
exports.handler = function(event, context, callback) {
const body = JSON.parse(event.body)
console.log('data: ', body.data)
}
Then apply the suggestions from #Marcin and fix your JSON data because it's missing quotes.
Your even.body is invalid json string, which explain why JSON.parse fails. Thus, you should check who/what is making the request and modify the code of the client side to invoke your API with a valid json string.
It should be:
'{"action": "message, "data": "black clolor"}'
not
"{action: 'message, data: 'black clolor'}"
Thanks #Marcin for the feedback, it was indeed caused by invalid json string sent from frontend.
Changing it to the code below solved the issue.
{"action": "message", "data": "black clolor"}
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.
I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.
You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});
I have a json object that i want to use.
{
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}
so when i try to access it using
console.log("Postback: " + payload.type)
but i get an error of
Postback: undefined
i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type
thanks in advance
Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.
So, let's say you have the following:
let payload = {
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzWadM"
}
You have to convert it into a JS object using JSON.parse:
let payloadObj = JSON.parse(payload);
Now, if you do payloadObj.type, you should be fine.
console.log(payloadObj.type); // PROVIDER_PAYLOAD
It should work fine.
UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0
If you are getting this error, try following to Parse the payload.
let payloadObj = JSON.parse(JSON.stringify(payload))
It should solve the problem for you.