Wait Servlet finish action, and update screen with js

Asked

Viewed 227 times

0

I pass a value to Servlet, with js, not to redirect the page:

      var formData = new FormData();
      var xhr = new XMLHttpRequest(); 
      xhr.open('POST', 'ServletMessage', true);
       xhr.send(formData);

and write this value in the database, the problem is that the page refreshes before writing in the comic, and the value does not change on the screen. How can I expect Servlet to record in the database, and then refresh the page?

1 answer

1

It is necessary to define a function to handle the event XMLHttpRequest.onreadystatechange. This event is triggered whenever the order status is changed. To do something when the request ends (status XMLHttpRequest.DONE), we do something like this:

var nome = document.getElementById('nome').value;
var postData = 'nome=' + encodeURIComponent(nome);

var xhr = new XMLHttpRequest(); 
xhr.open('POST', 'ServletMessage', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function () {
    if(xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200)
            console.log('Pedido concluído com sucesso, atualize a página');
        else
            console.log('Erro');
    }
};

xhr.send(postData);
  • How do I receive this value in Servlet, for example a text field? I’m trying, but it always comes null.

  • I modified my answer by including an example. In your code, formData was initialized but was sent without setting any value.

  • How do I call this function? and I can add an array of files?

  • To attach a file is used FormData same. To use this code block, you have to create the function first. From there, you specify the function in the event of an element directly or use the addEventListener (recommended).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.