[Solved-6 Solutions] Refresh a page with jQuery - javascript tutorial



Problem:

How to refresh a page with jQuery ?

Solution 1:

This solution refresh a page using as SetInterval() method to call the .reload() function.

<script>
    $(document).ready(function() {
        // SET AUTOMATIC PAGE RELOAD TIME TO 5000 MILISECONDS (5 SECONDS).
        setInterval('refreshPage()', 5000);
    });

    function refreshPage() { 
        location.reload(); 
    }
</script>
</html>

This solution set the time as 5000 milliseconds or 5 seconds.

Solution 2:

Using location.reload():

$('#something').click(function() {
    location.reload();
});

The reload() function takes an optional parameter that can be set as true given a force to reload from the server rather than the cache. While parameter defaults set as false, the page will reload from the browser's cache.

Solution 3:

Without jQuery this code should be work in all browsers.

location.reload();

Solution 4:

Using javascript, there are multiple ways to refresh a page:

  • location.reload()
  • history.go(0)
  • location.href = location.href
  • location.href = location.pathname
  • location.replace(location.pathname)
  • location.reload(false)

We want to pull the information from the web server again then we would pass the parameter set as true.

  • Here is the other way to reload the page with JavaScript
    • window.location = window.location
    • window.self.window.self.window.window.location = window.location
var methods = [
  "location.reload()",
  "history.go(0)",
  "location.href = location.href",
  "location.href = location.pathname",
  "location.replace(location.pathname)",
  "location.reload(false)"
];

var $body = $("body");
for (var we = 0; we < methods.length; ++i) {
  (function(cMethod) {
    $body.append($("<button>", {
      text: cMethod
    }).on("click", function() {
      eval(cMethod); 
    }));
  })(methods[i]);
}

CSS:

button {
  background: #2ecc71;
  border: 0;
  color: white;
  font-weight: bold;
  font-family: "Monaco", monospace;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.5s ease;
  margin: 2px;
}
button:hover {
  background: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 5:

Many ways to reload a page :

  • window.location.reload();
  • history.go(0);
  • window.location.href=window.location.href;

Solution 6:

This code will be trigger to reload a page using Ajax jQuery. The URL is " ", which means this page.

$.ajax({
    url: "",
    context: document.body,
    success: function(s,x){
        $(this).html(s);
    }
});


Related Searches to javascript tutorial - Refresh a page with jQuery