Skip to content
Advertisement

how to transfer data from sun to java

I have a form for sending first and last name to the js

index.html

 <body>
       <form name="loginForm" onsubmit="createUser()"> 
        <p > Firstname: </p>
        <input type="text" name="firstname" id="firstname" placeholder="firstname"/><br>
        <p > Lastname: </p>
        <input type="lastname" name="lastname" id="lastname" placeholder="lastname"/><br>
        <input id="loginButton" type="submit" value="Create User" >
    </form>
       <script> 
           function createUser() {
            let firstname = document.forms['loginForm'].elements['firstname'].value;
            let lastname = document.forms['loginForm'].elements['lastname'].value;
                }
    
          createUser();
     </script>

I want that when the create user button is clicked, the data is transferred to the backend and the user is created there.

   @PostMapping(value = "/save", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void save(@RequestBody Person person) {
        personService.save(person);
    }

i don’t understand how to redirect data from js to java.

I use MVC and spring boot

Advertisement

Answer

Vaniila JS Ajax: You can send an AJAX request from the client to the server. The POST request in this case sends JSON with 2 parameters: server-var-first-name, server-var-last-name

 function createUser() {
     let firstname = document.forms['loginForm'].elements['firstname'].value;
     let lastname = document.forms['loginForm'].elements['lastname'].value;
     var xhttp = new XMLHttpRequest();
     xhttp.open("POST", "ajaxfile.php", true); 
     xhttp.setRequestHeader("Content-Type", "application/json");
     xhttp.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
       // Response code
    }
};
    var data = {server-var-first-name:firstname,server-var-last-name: lastname};
    xhttp.send(JSON.stringify(data));
 }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement