user3607058 user3607058 - 20 days ago 10
Java Question

Exchange data between HTML page and Java servlet without page refreshing

I would like to create a simple login form with HTML and Java (and maybe JSON). So, I have a login form with several input fields with the following id-s: txtUsername, txtPasswd, btnLogin.
After click on the button (btnLogin) I would like to send data to the servlet, and get back just a true/false value deepends on the user-passwd combination.
I can write the HTML code of this form, and the server side code, but I don't know, how can I send and recive data without page refreshing.

Here is my frontend code:

<script>
function login(){
var user=document.getElementById("txtUsername");
var passwd=document.getElementById("txtPasswd");
//???
}
</script>


Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>

Answer

You have to use an AJAX request. One way of doing it is to wire up and event handler on a your login button (like onclick), which calls a JS function to use an Ajax request (XmlHttpRequest), just like you have started.

You can do it in vanilla Javascript, but it is easier to use a library like jQuery. The code would look something like this (with jQuery, note the '$'):

function login() {
    $.ajax({
        type: 'POST',
        url: url, //Url of login endpoint
        data: DATA, //Now here you would want to send a payload i.e. your username and password data
        dataType: 'json',
        contentType: 'application/.json',
        success: function(data) { 
                    //HERE 'data' would represent your true or false that came back from the server. 
                    //You can do stuff here with the response
                 },
        error: function(jqXHR, textStatus, errorThrown) {
                    //IF ERROR then this code would be executed.                        
               }
    });
}

Hope this gives you a starting point!

Comments