I have a php function which reloads one page in hidden iframe before real redirection is done after input button is clicked.
function button_confirm_order_params() {
$url = "somepagetoreloadinbackground.php";
$alert = "alert('you will be redirected to ext. page')";
return "onclick=\"document.all.myFrame.src='$url'; $alert;\"";
}
Everything works good, however I would like to use something more beautiful than browser's alert. So I downloaded SweetAlert and changed return to:
return "id=\"btnShowAlert\" onclick=\"document.all.myFrame.src='$url'; \"";
The problem is that without alert() the page is not being stopped before redirection. It's just shows sweetalert for a moment and then opens another page, so my "somepagetoreloadinbackground.php" is not loaded. Any ideas to handle it?
If you check the examples given on a sweetalert github, it seems there's actually alot of options that can help you: http://t4t5.github.io/sweetalert/
There's a standard timeout version: It's the timer attribute you have to add.
swal({
title: "some title",
text: "some message",
timer: 2000, // timeout in miliseconds
showConfirmButton: false // show ok button or not
});
And also, although it's a confirm instead of an alert, there's a callback function! Just add you redirect to that callback if the timeout version isn't good enough:
swal({
// add all options you want
},
function(){
// the actual callback, triggered by clicking the ok button on the confirm.
document.all.myFrame.src='$url'
});
Always read the docs for the library you're using first. :)
Related
I have the following beforeunload function which I have stolen from sonewhere else....
$().ready(function() {
$("#posManagerLoginForm").trigger("submit");
$(window).bind("beforeunload", function(){
window.setTimeout(function () {
window.location = "home.htm";
}, 0);
window.onbeforeunload = null; // necessary to prevent infinite loop that kills your browser
return "Press 'Stay On Page' to go to Reporting Manager home";
});
});
Regardless of what option I select I get navigated to home.htm. Is there a way that I can make the dialog box an ok button instead of the default "Leave Page" or "Stay on page" options?
Or perhaps someone else could make a suggestion on hot to better handle?
thanks
You cannot override the styling of the onbeforeunload dialog. Believe me, I tried this before in my earlier projects.
Reference: http://msdn.microsoft.com/en-us/library/ms536907%28VS.85%29.aspx
It is built into the browser object, and you have no control over it.
You can however set your own dialog to show when the onbeforeunload event triggers, but it will not disable that the regular one will show. Quite annoying, yes.
The reason you're still getting redirected is because you're actually doing nothing to prevent it.
If you want to open an alert box before the form gets submitted, make sure the default behaviour is prevented (which is to submit the form), then redirect after OK has been clicked like this:
$().ready(function() {
$("#posManagerLoginForm").submit(function( event ) {
event.preventDefault();
alert("Press 'OK' to go to Reporting Manager home");
window.location = "home.htm";
});
});
Though not sure what the use of this would be. If you wanted to stay on the form if a different button is pressed (say 'Cancel' for example), then you'd rather want to use a 'confirm' like this:
$().ready(function() {
$("#posManagerLoginForm").submit(function( event ) {
event.preventDefault();
if confirm(("Press 'OK' to go to Reporting Manager home"))
window.location = "home.htm";
});
});
You could replace the alert or confirm with a custom dialog box too, depending on what library you're using. Just make sure you put window.location = "home.htm" inside the dialog's function, otherwise it will execute immediately.
As an example, you may want to have a look into jQuery UI's dialog here: https://jqueryui.com/dialog/
I am developing a project where user gets a conformation page. I want user not to click back or close tab or reload.
Now either I need to disable the browser features or get back button,tab close event, or reload event to java script so that I could take the needed steps to prevent my data to get lost.
I have used this:
window.onbeforeunload = function()
{
return "Try This";
};
But this get called even when I click a button that redirects the page.
If you just want to have the alert, understanding that the user is ultimately in control and can bypass your alert, then do what you're doing but use a flag that disables it when you're navigating and don't want the alert. E.g.:
var warnWhenLeaving = true;
window.onbeforeunload = function() {
if (warnWhenLeaving) {
return "your message here";
}
};
then in a click handler on the link/button/whatever that moves the user on that you don't want this to pop up on:
warnWhenLeaving = false;
In a comment you asked:
can i know that what user has clicked when alert is generated with this function. That is can i know what user has clicked (leave this page/stay on page)
The answer is: Sort of, but not really; you're almost certainly better off not trying to.
But: If you see your onbeforeunload function run, then you know the user is leaving the page and the browser is likely to show them your message. The browsers I'm familiar with handle the popup like an alert: All JavaScript code on the page is blocked while the popup is there. So if you schedule a callback via setTimeout, you won't get the callback if they leave and you will if they stay:
window.onbeforeunload = function() {
if (warnWhenLeaving) {
setTimeout(function() {
display("You stayed, yay!");
}, 0);
return "No, don't go!";
}
};
Live Example
So in theory, if you get the callback, they stayed; if you see an unload event, they left. (Note that there are very few things you can do in an unload event.)
I've tried that on current Chrome, current Firefox, IE8, and IE11: It works on all of those. Whether it will work in the next release of any of them is anybody's guess. Whether it works reliably on mobile browsers is something you'd have to test, and again could change.
I have a form where people can delete records;
Delete Record 1
Delete Record 2
Delete Record 3
To ensure they are sure, I am using a "Are you sure" confirmation script (Popconfirm) which gives a nice little popup confirmation.
$(".confirm-action").popConfirm();
If the user clicks cancel, nothing happens. If they click 'yes' - the link is processed and the record deleted. This is working as intended.
Now instead of following the link (when the user clicks 'yes'), I want to fire an ajax request:
$('.confirm-action').click(function(event) {
event.preventDefault();
$.ajax({
// Ajax stuff here
});
});
$(".confirm-action").popConfirm();
The problem is when I try this, the functions are fired in the correct order when expected, except the event is null, so the script fails.
How do I "preventDefault()" when the event is null, and/or manually get the event to prevent the link from being followed by the browser?
Edit: JSFiddle showing the problem.
As noted in the comments, the plugin is horrible and plays with _data(events) IE plays with internal event management of jQuery.
If you aren't concerned about the UI, I would suggest you to go with normal confirm() as used in SO.
I've created this for you while typing this answer:
$.fn.nativeConfirm = function (options) {
return this.click(function () {
var bool = confirm(options.text);
bool ? options.yes.call(this) : options.no.call(this);
});
}
Example:
$('a').nativeConfirm({
yes: function(){
alert('yes');
},
no:function(){
alert('no');
},
text: 'Seriously?'
});
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.