how to access ejs object parameters in script file - javascript

I'm using express server with ejs templates for client and im passing an object not a single variable from server to client side.. like
router.get('/users/info',(req,res)=>{
let data = {
name:"myName",
email:"me#email.com",
address:"x,y,z",
coordinates:{ lat:34.545, lng:78.345 }
}
res.render('myEJSfile',{data});
})
In myEJSfile.ejs file
<div id="_data" data-params="<%=data.name%>"></div>
<script>
let data = document.getElementById('_data').dataset.params;
console.log(data);
</script>
OUTPUT : myName
which is expected output
But when I try to log whole object.. Again in myEJSfile.ejs :
<div id="_data" data-params="<%=data%>"></div>
<script>
let data = document.getElementById('_data').dataset.params;
console.log(data);
</script>
OUTPUT : [object Object]
here i want to display a complete valid object passed as a parameter from server side as i need to access on each and every attribute of this object seperately
Guys im stuck i have no other way in this particular situation get me out of this

Related

pass the list values from Flask to JS: TypeError--: Object of type 'Undefined' is not JSON serializable cannot be resolved

I am trying to send a list generated in Flask to Javascript.
But I kept having this same issue. TypeError: Object of type 'Undefined' is not JSON serializable
Please help me.
My flask code is:
jsonString = json.dumps(LstSNV.serialize())
return render_template("spatial.html", AO_sDocument=occu, snvLst=jsonString)
My js in html page is:
let dataset = {{snvLst|tojson|safe}};
I even try to get the list directly from the html but failed.
function myFunction() {
var oldValue = document.getElementById('submit').value;
console.log(JSON.stringify(oldValue));
document.getElementById("submit").innerHTML = "LOADING...";
}
I think this problem is my list is undefined but i dont know how to convert it.
Thank you.

Pass Spring model attribute to JS script

So, I'm having my data parsed to json and then put in the model attributes. Like this:
#RequestMapping("/{id}")
public String getNetworkDetails(Model model, #PathVariable String id) throws JsonProcessingException{
model.addAttribute("poolHashrates", findAndDisplayDataService.getAllPools(Long.valueOf(id)));
model.addAttribute("poolDataJson", findAndDisplayDataService.returnPoolsAsJson(Long.valueOf(id)));
return "networkDetails :: modalContents";
}
Next I'm trying to assign a poolDataJson string to a JS variable in html fragment through:
<script>
var data = eval('('+'${poolDataJson}'+')');
console.log(data);
</script>
What I would like to do with the data, is pass it to external JavaScript file as a data for my pie-chart. But first I'm getting an error on a string assignment:
Uncaught SyntaxError: Unexpected token {
What am I missing?
EDIT
I have also tried assigning json string to hidden input via:
<input type="hidden" id="networkId" th:value="${poolDataJson}"/></td>
And then read it with:
var data = document.getElementById('networkId').innerHTML;
console.log(data);
But again, nothing prints in console. When I put the ${poolDataJson} in it prints properly on a page...
You shouldn't be returning a String as JSON text. Instead, you should return regular Java objects and then evaluate it like this (thymeleaf will automatically convert objects to JSON):
<script th:inline="javascript">
var data = /*[[${poolDataJson}]]*/ {};
console.log(data);
</script>
As for your errors. I would have to guess that your method findAndDisplayDataService.returnPoolsAsJson is returning invalid JSON. Without a real example, it's hard to tell.

how can i make sure that my node js json doesn't send an 'undefined' when called by an http javascript

Ok, currently i've been having this problem. I'm trying to send a json file from my node server to my html javascript but its been getting an undefined. Here is the sample code:
server side:
app.get("/resources",(req, resp)=>{
resp.json({stuff:"goodbye"})
})
html javascript:
var slink = "http://localhost:3000/resources"
fetch(slink).then((resp)=>{
console.log(resp)
return resp.json;
}).then((json)=>{
console.log(json.data)
})
All of it runs but when console.log(json.data) runs, it returns an undefined. Any idea what went wrong?

save parsed JSON as obj

first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that I am able to 'get' the file throgh the use of jquery getJSON, in the callback i've tried to create a function that re-defines a global variable as an object containing the parsed data, but when I try to inject it into a document.getElemendtById('example').innerhtml = tgmindex.ToughGuys[1].name;
it returns a error "Uncaught TypeError: Cannot read property '1' of undefined"
here's my js/jquery
var tgmIndex;
$(document).ready(function () {
$.getJSON("http://webspace.ocad.ca/~wk12ml/test.json",function(data){
console.log( "success" );
tgmIndex =$.parseJSON;
document.getElementById('tgm1').innerHTML= tgmIndex.ToughGuys[1].name;
});
});
and here is whats contained in the JSON (i made sure to try linting it first and it's a valid json)
{"ToughGuys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":" original Intern"}
]}
You're setting tgmIndex to the parseJson function.
Should be doing tgmIndex =$.parseJSON(data);
Presumably your service is returning application/json. Therefore data already contains the json.
tgmIndex = data;
Then... "Tough Guys" is what you should be indexing. Not "ToughGuys"
Your example JSON is wrong in your question. If I go to
http://webspace.ocad.ca/~wk12ml/test.json
I see:
{"Tough Guys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":"Intern 0"}
]}
See "Tough Guys" There's your problem.
document.getElementById('tgm1').innerHTML= tgmIndex['Tough Guys'][1].name;
If data for some reason isn't JSON:
tgmIndex = $.parseJSON(data);

How can I pass JSON to client using Node.js + HBS + Express?

Consider, I am sending JSON to client as follows in render page of Express (using hbs as a view engine):
res.render('MyPage.html', { layout: false, PageTitle: 'Project Name', JSON_Data: {field1:'value',field2:'value2'}});
I am able to access and set title of html page by using {{PageTitle}}, following is the code.
<title>{{PageTitle}}</title>
Now I want to show JSON_data into alert popup.
I've tried following way, but getting Uncaught SyntaxError: Unexpected token {, while debugging in chrome is shows var jsonobj = [object Object]
function fbOnBodyLoad() {
var jsonobj = {{JSON_data}};
alert(jsonobj);
}
Could any body give some idea on How to access JSON_data and show in alert
Advance Thanks
to access the inner elements of the json object, try like this
var jsonobj = "{{JSON_data.field1}}";
may be this might solve the issue.
refer
Handlebars.js parse object instead of [Object object]
You could always register a Handlebars helper to format the object into a string format (such as by using JSON.stringify), and then use that helper in your view. http://handlebarsjs.com/block_helpers.html
For me it worked by doing in the server:
res.render('pages/register', {
title: 'Register Form',
messages: req.flash('error'),
countries:JSON.stringify(countries)
});
and then I used this countries variables to assign in angular controller like this:
angular.module('languagesApp', []).controller('DemoController', function($scope) {
$scope.algo = {{-countries}};
...

Categories

Resources