Search code examples
javascriptjqueryhtmlspringthymeleaf

How to send parametr to Controller properly? (Thymeleaf + Javascript)


I am beginner at Thymeleaf. All I know is the fact that "Thymeleaf is not Javascript, it is rendered on server." I am making mistakes all the time because I am usually trying to use that Thymeleaf a little like JavaScript.

HTML

<form th:action="@{/user/sqlCode}" method="post">
    <button id="newDatabase"></button>
</form>
<textarea id="generatedSql" readonly></textarea>

Controller

@PostMapping(path = { "/user/sqlCode" })
public String createSchema(@RequestParam(???) String tmp) {
    String finallyMyValue = tmp;
    // STOP  I want to have data from generatedSql in this moment (finallyMyValue)
    // ...
}

@ MISSION @
1. Click button (id: newDatabase)
2. Get data from the textarea (id: generatedSql)
3. Send the value with that data to the controller
4. Be happy :)
@ MISSION @

I tried a lot of things but only using Javascript. Scenario is always the same, JavaScript is executed totally before Thymeleaf and finally I can't properly read that data... I tried that scenario:

  1. Click button (id: newDatabase)
  2. Get data from the textarea (id: generatedSql) using JavaScript
  3. Insert that data into variable name in input tag using JavaScript
  4. Send the variable name to the controller.
  5. And here I always get NULL or error 404

Screenshot with my failed approach, which ended in a null at the breakpoint: enter image description here


Solution

  • I think you should try use Javascript with Ajax:

    <div>
        <button type="button" onclick="submitData()">Change Content</button>
    </div>
    
    function submitData() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
        xhttp.open("post", "$URL", true);
        xhttp.send();
    }