Niranjan Dattatreya
Niranjan Dattatreya

Reputation: 485

In java spring boot how to pass form action as a function using thymeleaf, ,How to parse form action as a function

In my spring boot application I need to submit a form and the form action should be a function. This is the code I tried:

The html code for submitting form:

<form role="form" id="form_id" data-parsley-validate="" novalidate=""
                        class="mb-lg" th:action="get_action()" method="get">

The javascript function:

function get_action(){
    $("#form_id").attr("action"); //Will retrieve it

    $("#form_id").attr("action", "@{/changePassword1}"); //Will set it

}

This is the error I am getting "There was an unexpected error (type=Internal Server Error, status=500). Could not parse as expression: "get_action()" (admin:55)"

How should I solve this, so that I can pass a form action as a function?

Upvotes: 0

Views: 2643

Answers (2)

Gendo90
Gendo90

Reputation: 11

This is answered here - using Thymeleaf's inline scripting feature!

Change a form's action dynamically on thymeleaf

Upvotes: 1

Oskar Dajnowicz
Oskar Dajnowicz

Reputation: 1770

You are messing things up, thymeleaf is rendering view by server side and javascript is executed on the client-side, the th:action is expecting to get some themeleaf expression (e.q @{/changePassword1}).

If you want to change the action url using javascript you need to place this script in some html file in tags at the bottom so thymeleaf can render your thymeleaf variables.

You need to invoke your javascript url change somewhere, I don't know what causes(you didn't specify) the url change so i guess it can be invoked after the page is loaded(e.q jQuery $(document).ready()) or caused by some event(button click)

EDIT

     <form role="form" id="form_id" data-parsley-validate="" novalidate=""
                            class="mb-lg" th:action="@{/changePassword}" method="get">

and your modified example js

<script>
$(function(){
    function get_action(){
       //Will retrieve it
       console.log("form action url:" + $("#form_id").attr("action")); 

       $("#form_id").attr("action", "@{/changePassword1}"); //Will set it

    }

    get_action();
});
</script>

Upvotes: 0

Related Questions