Why does not this setTimeout work?

0

My goal is when I click the button, 3 seconds later a div reread page ...

Why does not this code work?

<button id="btn-cadastra-tarefa" ng-click="adicionaTarefa()" onclick="atualiza()" 
        type="button" data-dismiss="modal" >
    <span class="glyphicon glyphicon-ok-sign"></span>Salvar
</button>

<div id="atualizaPagina"></div>

function atualiza() {
    setTimeout(function(){ $('#atualizaPagina').location.reload(); }, 3000);
}
    
asked by anonymous 28.07.2017 / 14:44

2 answers

2

If you really need to upgrade the entire page you can use:

It works in IE:

setTimeout(function(){ window.location.href = window.location.href; }, 3000);

I have not tested on all browsers, it may not work on some:

setTimeout(function(){ location = '' }, 3000);
setTimeout(function () { location.reload(); }, 3000);

To reload a page via javascript you can use one of the following options:

Javascript 1.0

window.location.href = window.location.pathname + "pagina";
  

Create page history entry

Javascript 1.1

window.location.replace(window.location.pathname + "pagina");
  

Do not create page history entry

Javascript 1.2

window.location.reload();
  

Reload cache page

window.location.reload(false);
  

Reload cache page

window.location.reload(true);
  

Reload server page (new GET force)

    
28.07.2017 / 15:42
5

Mostly because it does not make sense.

$('#atualizaPagina') returns an HTML element and no HTML element has the location property, consequently, the reload() method does not exist.

If you want to refresh the entire page use window.location.reload() . There is no method of updating a div, because it would not make sense. Would you upgrade based on what?

What you should really want to do is just modify the data that is shown in this div, so you need to make a Ajax call pro backend and then refresh the div via JavaScript based on the response of your Ajax call.

I can not show an example with code because this part of the code does not exist in the question.

See a generic example that makes an Ajax request and then updates the img tag:

const reqUrl = 'https://api.giphy.com/v1/gifs/search?api_key=9e4393bfcf774cd08e0757b4688b11f7&q=javascript';

$('#ajax').on('click', function() {
  $.get(reqUrl, function(r) {
    $('#img').attr('src', r.data[0].images.original.url);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="ajax">Faça uma requisição Ajax</button><br>

<img id="img" src="http://netcoders.com.br/wp-content/uploads/2015/10/js3.png"width="250" height="250" />
    
28.07.2017 / 14:53