GaneshSreeju GaneshSreeju - 27 days ago 5
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 %>);" > <%=book.name %></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

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)%>);"><%=book.name %></button>
<% }); %>

You're fine using <%=book.name%> because that should output a string.

Comments