I'm trying to send JSON-object form MongoDB to page with ejs template engine. Here's the response form my DB (a JSON-object):
"suppliers": [
{
"lastname": "lastname1",
"firstname": "firstname1",
"middlename": "middlename1",
"mobtel": "mobtel1",
"worktel": "worktel1",
"email": "email1"
},
{
"lastname": "lastname2",
"firstname": "firstname2",
"middlename": "middlename2",
"mobtel": "mobtel2",
"worktel": "worktel2",
"email": "email2"
}
]
As I get i from DB as an object, I have to stringify it to str to send as a var for EJS Template engine:
var myJSONText = JSON.stringify(doc.suppliers);
profile["suppliers"] =myJSONText;
...
res.render('profile.ejs',{profile:profile});
On front-end I get a plain string with json-data. I parse it via jQuery to an object:
var jsonObject = jQuery.parseJSON('<%= profile.suppliers %>');
for (var i=0; i<jsonObject.length; i++){
//trying to show field 'name' for every supplier
alert(jsonObject[i]['lastname']);
}
...and it doesnt work, but should to alert me twice. I've tried to inspect a plain-text JSON-string, comming to front-end, and found out such symbols:
[{"lastname": " ...
It seems that jQuery.parseJSON is not able to create a valid object from such string. What I'm doing wrong? Thanks!
UPDATE: Well, I've turned my code into:
NodeJS code:
profile["suppliers"] =doc.suppliers;
res.render('profile.ejs', { profile:profile });
jQuery code:
for (var i=0; i<'<%= profile.suppliers %>'.length; i++){
//trying to show field 'name' for every supplier
alert('<%= profile.suppliers %>'[i]['lastname']);
}
and it gives me never-ending loop of undefined alerts.
UPDATE 2: I've updated my source code, so:
NodeJS:
var myJSONText = JSON.stringify(doc.suppliers);
profile["suppliers"] =myJSONText;
res.render('profile.ejs',{profile:profile});
Client:
var jsonObject = <%- profile.suppliers %>;
$.each(jsonObject, function(item) {
alert(item.lastname);
});
Generated source code:
var jsonObject = [{"lastname":"lastname1","firstname":"firstname1","middlename":"middlename1","mobtel":"mobtel1","worktel":"worktel1","email":"email1"},{"lastname":"lastname2","firstname":"firstname2","middlename":"middlename2","mobtel":"mobtel2","worktel":"worktel2","email":"email2"}];
Seems to be ok, but still gives me undefined alerts. Hoever, it alerts only twice, that means that it parses JSON correctly and just cannot get access to lastname property?
i<'<%= profile.suppliers %>'.length. You're iterating over the length of a string, not an array of objects.