Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

516
Views
Pass object to javascript function from ejs

I'm trying to attach a click event from my ejs file but I noticed that when my data coming from my database has a "newline", I get an error that says: Unexpected token in JSON at position 253

app.js

app.get('/', async (req, res) => {
   return res.render('page', {
      data: dataArray
   })
});

page.ejs:

  <% for(let t of data) { %>
  <tr class="tr-<%= t.id %>">
    <td><i class="fas fa-pencil-alt" onclick="editT('<%= JSON.stringify(t) %>')"></i>
    </td>
    <td><%= t.name %></td>
    <td><%= t.description %></td>
  </tr>
  <% } %>

script

function editT(t) {
  t = JSON.parse(t);
  console.log(t)
}

When a description has a "newline" and I use JSON.stringif(t) it comes broken:

let t = '{"id":1,"name":"Lorem","description":"Lorem Ipsum is simply dummy text of the printing and typesetting industry!

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum is simply dummy text of the printing and typesetting industry.
","created_at":"2022-04-18T22:19:00.153Z"}';


console.log(JSON.parse(treatment));

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

there two way of doing this without error

first one using <%- %> this way it will write the unescaped string

like this :

<td><i class="fas fa-pencil-alt" onclick="editT('<%- JSON.stringify(t)%>')"></i></td>

second one would be using encode

<td><i class="fas fa-pencil-alt" onclick="editT('<%= encodeURIComponent(JSON.stringify(t))%>')"></i></td>

the second one also requires you to do

function editT(t) {
  t = JSON.parse( decodeURIComponent(t));
  console.log(t)
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!