Reputation: 762
Is there any way to implement a callback for a page refresh function, check if the page is ready after it is refreshed and then print a message? I'd like to show refresh the page and show a certain message after clicking a button, however, I need to stay within my code in order to know what message to show. Anything similar to the next code would be great:
location.reload(function(){
alert ('done refreshing and document is ready');
});
Upvotes: 6
Views: 28799
Reputation: 2736
If you want to user window.location.reload() you have to use Browser's sessionStorage. Here is my code, I use this for saving data.
window.onload = function () {
var msg = sessionStorage.getItem("nameShah");
if (msg == "Success") {
sessionStorage.setItem("nameShah", "");
alert("Saved Successfully");
}
}
$("#save").click(function () {
$.ajax({
url: "/AspNetUsers/SaveData",
type: "POST",
async: true,
data:{userName: "a"},
success: function (data) {
if (data.Msg == "Success") {
sessionStorage.setItem("nameShah", "Success");
window.location.reload();
}
}
});
});
Server Side:
public ActionResult SaveData(string userName)
{
return Json(new { Msg = "Success" }, JsonRequestBehavior.AllowGet);
}
Upvotes: 1
Reputation: 1336
If you really want to go javascript side, you can use sessionStorage.varName before reloading, and then you check that var and continue.
Upvotes: -1
Reputation: 820
The way to go is using
$(document).ready(function(){
alert('done refreshing and document is ready');
});
But it doesn't differentiate a first load from a refresh. But you could achive that using sessions. For example, using PHP:
<?php
session_start();
$showJs = false;
if( !isset($_SESSION['loaded_before']) ) {
$showJs = true;
$_SESSION['loaded_before'] = true;
}
?>
...
<?php if($showjs) { ?>
<script type="text/javascript">
$(document).ready(function(){
alert('done refreshing and document is ready');
});
</script>
<?php } ?>
Upvotes: -1
Reputation: 42440
On page reload, your JS application gets re-initialized and starts all over again, so you cannot have a callback.
However, what you can do is add a hash fragment to the URL before reloading.
window.location = window.location.href + "#refresh";
window.location.reload();
Then, on page load, check if the hash fragment exists. If it does, you'll know you just refreshed the page.
Upvotes: 13