1

I need to call a javascript function from html using thymeleaf. In this particular case I have a student object and I need to pass this student object to a javascript function (edit()) for processing on button click.

Important code segments:

<form action="/addStudent" method="post">
Name:<br>
<input type="text" id="name" name="name"><br>
<input type="submit" value="Submit"></form>


<table>
<tr>
    <th>ID</th>
    <th>Name</th>
</tr>
<tr th:each="student : ${students}">
    <td th:text="${student.id}"></td>
    <td th:text="${student.name}"></td>

    <td>
        <button type="button" th:onclick="'edit(\'' + ${student} + '\');'">Edit</button>
    </td>
</tr></table>

<script type="text/javascript">
function edit(student)
{
    console.log("--------------------edit---------------------" + student.name);
}</script>

But it doesn't work as expected. It shows the following error. Can anyone help by showing how to pass student object from thymeleaf to javascript function?

There was an unexpected error (type=Internal Server Error, status=500).An error happened during template parsing (template: "class path resource [templates/students.html]") org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/students.html]")

3
  • What do you mean not as expected? Do you get the student obj correctly inside the edit function? Commented Sep 25, 2019 at 6:48
  • @Eytan updated the original post with error message. Commented Sep 25, 2019 at 7:48
  • Check what student is in the edit function. Add debugger; at the beginning of the function. Press F12 or Ctrl+Shift+I to catch. Commented Sep 25, 2019 at 12:32

1 Answer 1

2

For security reasons you've to define the parameter to use as a data attribute (in the newest versions of thymeleaf). Do it in the following way:

th:data-student="${student}" th:onclick="edit(this.getAttribute('data-student'))"
Sign up to request clarification or add additional context in comments.

3 Comments

This works pretty well, but only for strings. If I try to get student property name it says undefined. Can we pass the whole student object so that javascript function can access its all attributes?
@Ruchira the easiest way is probably to use JSON format in the data attribute, then retrieve it in js. Look at this fiddle: jsfiddle.net/GlauberRocha/Q6kKU
Will try that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.