Wait for servlet to complete action, and refresh screen with js

0

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

and I write this value in the database, the problem is that the page refreshes before writing to bd, and the value does not change on the screen. How can I wait for the servlet to write to the database, and then the page refresh?

    
asked by anonymous 06.04.2016 / 21:45

1 answer

0

You need to set a function to handle the event XMLHttpRequest.onreadystatechange . This event fires whenever the order status changes. To do something when the request is finished (state 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);
    
07.04.2016 / 02:13