i want to put this dialog box inside the page refresh. i mean. when i refresh the page this must be the out put.
<script>
$(function() {
$("#dialog").dialog({
modal: true,
resizable: false,
buttons: {
"I want to Continue the Exam": function() {
$(this).dialog("close");
},
"I Refresh": function() {
$(this).dialog("close");
}
}
});
});
</script>
As far as I know, when you 'refresh' a page then all the JS objects are destroyed (those that are written in script).In other words the script is re-loaded. So you can't persist your script while the page is in transition.
Type I (classical Single Page App)-
So if you simply want to reload a particular part of the Application then use $.ajax() methods like beforeSend() for showing whatever (alert or best a loading spinner/div) you want during the data request or 'page-refresh'. And then you can hide them on done().
Type II (using routers)
JS frameworks like Angular give you options to reload a particular route of your App without reloading/refreshing your entire app - $route.reload(). You can show/hide some div/directive based on manipulation in your controller.
So you have to use some form of asynchronous scripting to deal with this "PROMPT while REFRESH" situation.
Using $.ajax() to simulate (pseudo code)-
$.ajax({
url: "_URL_to_get_or_post_data__",
beforeSend: function( xhr ) {
$popup.show();
}
})
.done(function( data ) {
$popup.hide();
}
});
Browsers have a security feature that will not let a page prevent users from leaving the page. By leaving a page it means closing tab/browser, navigating to a different page or refreshing. The only way to stop the user is to assign a function to onbeforeunload. Like this:
onbeforeunload = function () { return "You have unsaved data. Are you sure you want to exit?"; }
This message is synchronous, it will stop all javascript running on the page. If user presses ok the browser will leave the page (or refresh) else it will stay on the page.
EDIT
Usage: when user have changed something and have unsaved data - you assign a function to onbeforeunload:
onbeforeunload = function () { return "some message"; }
after the data is saved set onbeforeunload to null:
onbeforeunload = null;
Related
I am working on a single page application at the moment, and I wanting to show some UI is a user, refreshes the page, closes the tab, or navigates away, the reason for this is doing any of these will cancel any active uploads, and I want the user to know that.
So far I have,
$(window).on('beforeunload', function() {
alert("!!!");
return null;
});
This only seems to fire when I refresh the page, though. Is there away to hook this in to my router? I have a global var called App.Uploading, if that is true, I want to fire a method every time a route is accessed is that possible?
There is a JQuery unload function you can use:
$( window ).unload(function() {
console.log('preventing unload!');
return false;
});
document.location = 'http://www.google.com';
I have the following code
<script type="text/javascript">
function PopIt() { return 'Are you sure you want to leave?'; }
function UnPopIt() { /* nothing to return */ }
$(document).ready(function() {
window.onbeforeunload = PopIt;
$('a').click(function(){ window.onbeforeunload = UnPopIt; });
});
</script>
This script works. But how do I alter it so it works like this;
1) User presses exit tab/page
2) page changes to one of my choice
3) exit popup displays with yes or no to leave
4) yes = close page, no = stay on current page
I'd like the page to change before the popup displays
Thanks.
Note: I do have control over the pages, I wish to redirect to another .php in the same folder.
Try using both onbeforeunload and onunload together like this...
function PopIt() {
return 'Are you sure you want to leave?';
}
function UnloadIt() {
window.opener.nowDoThisOpener("pass this variable along too");
}
$(document).ready(function() {
//set the function defining what should be done BEFORE unloading
window.onbeforeunload = PopIt;
//set the function defining what should be done ON unloading
window.onunload = UnloadIt;
//set all links to disable both of these on click
$('a').click(function(){
window.onbeforeunload = null;
window.onunload=null;
});
});
Note that nowDoThisOpener is a function that you can define (And obviously call whatever you want) on the parent page. And, like I've suggested, you can pass along information too.
Also, in your example you were setting an empty function UnPopIt to cancel the onbeforeunload. That's unnecessary, you can just set the onbeforeunload to null, as well as the onunload, as I've done in my example.
Previous Answer:
Could you put some kind of flag in the hash when you redirect? So instead of sending off to http://www.pageofmy.com/choice.php you sent to http://www.pageofmy.com/choice.php#1
Then on choice.php you could have...
<script>
if (location.hash=="#1") {
//show alert
}
</script>
This assumes that you have control over pageofmy.com/choice.php. If you're redirecting to some other site you don't have control over, I don't see how you can do this besides attempting to have a popup window come up (which will most likely be blocked by modern browsers)
I am using jQuery's UI Dialog to draw a dialog (my-ui-dialog) to the screen and present the user with some <input>s and other controls. When the user clicks the dialog's OK button, I want the UI dialog to fire an AJAX/JSON message to my server (via getJSON), allow the server to process that call, and then close the dialog after the response is received from the server. Then the user should be redirected (via window.location) to another web page.
Here's my code:
$("#my-ui-dialog").dialog({
modal: true,
autoOpen: false,
height: 255,
width: 300,
buttons: {
"OK" : function() {
var f = $("#fizz").val();
$.getJSON(
"/myserver/do-something",
{
fizz: f
},
function() {
$("#my-ui-dialog").dialog('destroy');
}
);
// When I leave this in the code works great.
// When I comment the alert out, the getJSON call never
// hits the server-side.
alert("Returned from the backend...");
window.location = "/myserver/some-other-url"
$(this).dialog("close");
},
Cancel : function() {
$(this).dialog("close");
}
}
});
When I leave that alert box in, and wait a few seconds (with the alertbox drawn to screen), the getJSON method seems to have enough time to hit the server and return. But if I comment out the alert the request never even hits my server. I can tell this by adding a log message to the beginning of the handler listening at /myserver/do-something. This is also a Java web app and I don't see any evidence of Tomcat receiving the request, and I don't see the HTTP request being generated when using Firebug to debug. All 3 of these indicate that the request is simply not hitting the server at all.
What are my options here? Can I make the jQuery sleep for a few seconds? That feels like an ugly solution; there must be a better way to use the jQuery API... thanks in advance!
Put your dialog close and window.location code in the getJSON callback. That's why there's a callback.
I have a page where user needs to enter some data and click save to validate the changes, but my problem is if the user is trying to close the browser window or click on a different link to navigate to a different page..I need to delete all the entries the user has saved so far..
I am doing it the following way
window.onbeforeunload = function()
{
if(confirm('Are you sure you want to navigate'))
{
//Invoke `enter code here`server side method
}
else
{
// return false;
}
}
Everything works fine if he click on Yes, the problem comes when he click on "No"..Even if he click on No..the page unload method is getting called and it is redirected to a different page..but I want it to stay in the same page in same state...can you please help me in achieving this.
Thanks and appreciate your response....
You cannot stop the user from leaving the page. What you can do is alert a message to them, asking if they want to leave or not.
The window.onbeforeunload event should return a string (and only a string). This string will be printed on the alert box made by the browser.
You cannot use your own alert box, or block the user from leaving (or redirect them).
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
When a user leaves the page, you can use the onunload event to make an AJAX call (you may need to use async: false here).
Example:
$(window).unload(function(){
$.ajax({
url: '/path/to/page/',
async: false, // this may be needed to make sure the browser doesn't
// unload before this is done
success: function(){
// Do something
}
});
});
NOTE: Instead of doing this, why don't you just save everything when the user is completed? Instead of saving it and then removing it if the user doesn't finish?
First of all: you can't! It's impossible. onbeforeunload only accepts a string as return value and will then close if the user wants that.
But then think about what happens if the computer is being without energy and shuts down? Or the browser will closed by the Task Manager? Or even more "realistic": The internet connection get lost! => Then you got invalid data states too!
You are trying to solve a false problem! Your problem isn't this function, your problem is the state of your formular!
Why do you need some kind of function? Do you saving the data before he clicks on save? Then don't! Or make sure to have another query which detects unfinished data in your database and delete it after a timeout!
onbeforeunload only accepts a string as return value. That string will be displayed by the browser with the option to stay on the page or leave it. But that's ll you can do.
You can use something like this, just call the following function on your page
function noBack() {
window.onbeforeunload = function(){window.history.forward()}
}
this disables Back button if window.history is clean, otherwise it works only first time.
I have a handler for onbeforeunload
window.onbeforeunload = unloadMess;
function unloadMess(){
var conf = confirm("Wait! Before you go, please share your stories or experiences on the message forum.");
if(conf){
window.location.href = "http://www.domain.com/message-forum";
}
}
but I'm not sure how to know if the url they clicked on the page is within the site.
I just want them to alert them if they will leave the site.
It's not possible to do this 100% reliably, but if you detect when the user has clicked on a link on your page, you could use that as a mostly-correct signal. Something like this:
window.localLinkClicked = false;
$("a").live("click", function() {
var url = $(this).attr("href");
// check if the link is relative or to your domain
if (! /^https?:\/\/./.test(url) || /https?:\/\/yourdomain\.com/.test(url)) {
window.localLinkClicked = true;
}
});
window.onbeforeunload = function() {
if (window.localLinkClicked) {
// do stuff
} else {
// don't
}
}
I've got one idea, but I don't know if it's work. My suggestion is, add each link an onClick event with a function call. That function reads just the href attribute and store into a variable with global scope.
var clickedHrefAttrValue = "";
function getClickUrl(currentLink)
{
clickedHrefAttrValue = $(currentLink).attr("href");
return true;
}
The html for the a tags must be looks like following:
Linktext
and in your given function:
function getClickUrl()
{
if (clickedHrefAttrValue.indexOf("<your condition>" > -1)
{
//what ever you want do to
}
}
It is just an idea, but I think it is worth to try it.
If you are having issues because your website may have both absolute and relative local links, I have another solution (using jQuery):
Demo
/* EXTERNAL LINK WARNING
=========================================*/
$('a').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href'),
host = location.host;
if (url.indexOf(host) > -1 || url.indexOf('http','https') == -1){
/* If we find the host name within the URL,
OR if we do not find http or https,
meaning it is a relative internal link
*/
window.location.href = url;
} else {
var warn = confirm('You\'re leaving the domain.\n\nAre you sure?');
if(warn == true) {
window.location.href = url,'_blank';
} else {
e.preventDefault;
}
}
});
So I needed to do this so I could log a user out if they left the site from any page, but not if they navigate within the site. Here is my solution using JS and PHP
On every page where they need to remain logged in, set a session variable:
<?php
session_start();
$_SESSION["isInSession"] = true;
?>
Now create two scripts:
clear-in-session.php
<?php
session_start();
unset($_SESSION["isInSession"]);
?>
logout.php
<?php
session_start();
if(isset($_SESSION["isInSession"]) exit();
//do logout code here
?>
Now we set 2 events in JS:
window.addEventListener('beforeunload', function(event) {
$.ajax({
type: 'POST',
async: false,
url: 'clear-in-session.php'
});
});
window.addEventListener('unload', function(event) {
$.ajax({
type: 'POST',
async: false,
url: 'logout.php'
});
});
To explain the order of events when the user navigates to another page in the same site:
The user navigates away
beforeunload is triggered, calling clear-in-session.php which removes the isInSession variable
The new page is loaded, setting isInSession to true
unload is triggered, calling logout.php, but because isInSession has been set back to true, the logout code is never called
When the user navigates to a page outside of the site (or to any page on the site that doesn't set isInSession):
The user navigates away
beforeunload is triggered, calling clear-in-session.php which removes the isInSession variable
The new page is loaded
unload is triggered, calling logout.php, isInSession has been deleted, so the logout code is called
Sorry for necro but this thread still comes up when searching for the answer to this question
Note: This answer uses jQuery for post calls to the php. It is entirely possible to do this in pure JS, but it was easier to illustrate in jQuery
There is a good solution to this which I implemented in my website recently. Just imagine this, everything thats going to be in your website that navigates the user is either going to be a link (anchor tag), button, clickable image or something on these lines. Its definitely not going to be the body element.
Now what happens when a user leaves the website, he/she can either type in a url and press enter, click a bookmark or press the back/forward buttons.
When a user does do that, do this:
$(window).on('beforeunload', function(e)){
if(e.target.activeElement.nodeName.toLowerCase() == 'body'){
yourFunction();
});
What happens is that the body becomes the active element in the target in these cases (when user leaves the website) and this is not the case when the user clicks on internal website navigable elements.
This is a clean, easy solution. Let me know if you face any issues.