GaneshSreeju GaneshSreeju - 1 year ago 126
Javascript Question

How do I pass a JSON object to inline javascript In EJS

I just want to send EJS object to javascript function. I have tried below code but it didn't work.

<% books.forEach(function(book){ %>
<button onclick="getBookDetails(<%=book %>);" > < %></button>
<% }); %>

My JavaScript code is

function getBookDetails(book){
//using book object

I have tried following stuff also.But it didn't help.
getBookDetails(<%=JSON.stringify(book) %>);

Please help me to find the mistake.

Answer Source

You can't call getBookDetails(<%=book%>) because <%=book%> will get evaluated as [object Object] and not { name: "Wind in the willows, author: "Kenneth Grahame" } as you require.

You're on the right lines with using JSON.stringify but missed one crucial point: using <%= will escape html entities. Instead - use <%- like so:

<% books.forEach(function(book){ %>
    <button onclick="getBookDetails(<%-JSON.stringify(book)%>);">< %></button>
<% }); %>

You're fine using <> because that should output a string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download