0

I am learning expressjs,mongodb using nunjucks template.An array is sent from server to html in the following way:

poll.find().sort({'date': -1}).toArray(function(err,docs){
        res.render("home",{polls:docs});
    });

The variable polls is an array of objects.I am able to access the polls array successfully in the html view but I don't know a way to access it in the client side js file to draw charts using the data inside array.

If I use <input type='hidden value='{{ polls }}'>, it is converted to a string and the array, objects inside it cannot be accessed in client js. What can be done?

R-R
  • 317
  • 1
  • 6
  • 18

2 Answers2

0

i dont know what nunjucks does, but express sends all non-scalar data (= objects & arrays) as an JSON-string.

just use something like

var body = JSON.parse(responseText);

on the client to get the original object/array back.

alangecker
  • 21
  • 3
  • Should we get 'responseText' from HTML? If so,the array of objects is converted to string and JSON.parse unable to retrieve. – R-R Jan 11 '16 at 16:50
0

To make it accessible correctly you need to output polls via JSON.stringify which will convert your javascript array to the json format: JSON.stringify(polls).

So,

<input type="hidden" value="{{ JSON.stringify(polls) }}" />

Or to access it in javascript:

<script>
    var polls = "{{ JSON.stringify(polls) }}";
</script>

Or it will be even better to do this operation on the server side to make it faster (instead of client-side):

res.render("home", { 
  polls: JSON.stringify(docs)
});
oleh.meleshko
  • 4,675
  • 2
  • 27
  • 40
  • I tried ``, it gives **Error: Unable to call `JSON["stringify"]`, which is undefined or falsey** – R-R Jan 11 '16 at 17:03
  • For your 2nd suggestion script part, the 'polls' cannot be accessed from the js file like we do in html, {{ poll }} not working. – R-R Jan 11 '16 at 17:07