Get event after function complete - javascript

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?'
});

Related

How to disable browser feature

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.

How to disable Jquery prompt save button on first click

I am using jQuery prompt to prompt a user to save. So, a user clicks a Save button, the Jquery prompt displays and asks if the user is sure he/she wants to save changes or not. The problem is, the user is able to click multiple times on the jQuery Save prompt button before the prompt closes. As a result, my save routine runs once for each time the prompt save button is clicked, which results in duplicate records in the database. I need to disable the prompt save button on the first click or simply close the prompt window on the first click to prevent multiple saves. How can I do this?
Client code:
$.prompt("Are you sure you want to save? You will not be able to change your decision after it's been saved.", {
title: "Save?",
buttons: { "Save": true, "Cancel": false },
submit: function (e, v, m, f) {
if (v) {
response = saveUpdates(LoanDetails);
}
}
});
I created a fiddle here: http://jsfiddle.net/smurphy/4fqjR/
The solution is a little convoluted. I thought there would be a simpler way to do it but after looking through the documentation I cannot find any built in feature.
Here is the code:
submit: function (value, message) {
if (value) {
$(message.prevObject)
.find('button[value="true"]')
.attr('disabled', true);
//TODO: perform save
//response = saveUpdates(LoanDetails);
}
}
The message param is a reference to the text description so you can find the button by navigating around the DOM from that starting point.
Try to use a global variable as a flag,
or disable the prompt button (if you are using a button to call the prompt)
$("#promptbutton").prop("disabled",true);
Edit:
The easier solution is to simply close the prompt right before calling the saveUpdates function, or at the start of the function:
jQuery.prompt.close();

How to stop unloading the page?

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.

jQuery Exit Popup Redirect?

So I've been looking around for hours, testing multiple versions, testing some of my own theories and I just can't seem to get it working.
What I'm trying to do is use alert or confirm (or whatever works) so popup a dialog when a user tries to navigate away from a purchase form. I just want to ask them "Hey, instead of leaving, why not get a free consultation?" and redirect the user to the "Free Consultation" form.
This is what I have so far and I'm just not getting the right results.
$(window).bind('beforeunload', function(){
var pop = confirm('Are you sure you want to leave? Why not get a FREE consultation?');
if (pop) {
window.location.href('http://www.mydomain/free-consultation/');
} else {
// bye bye
}
});
$("form").submit(function() {
$(window).unbind("beforeunload");
});
This is showing confirm dialog to user, want to stay or leave page. Not exactly what you looking for but maybe it will be useful for start.
function setDirtyFlag() {
needToConfirm = true; //Call this function if some changes is made to the web page and requires an alert
// Of-course you could call this is Keypress event of a text box or so...
}
function releaseDirtyFlag() {
needToConfirm = false; //Call this function if dosent requires an alert.
//this could be called when save button is clicked
}
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
Script taken from http://forums.devarticles.com/showpost.php?p=156884&postcount=18
Instead of using the beforeunload and alert(), I decided to check whether or not the users mouse has left the document. See code below:
$(document).bind('mouseleave', function(event) {
// show an unobtrusive modal
});
Not sure whether it will help.
You need to stop the propagation before showing the Confirm / Alert.
Please refer http://jonathonhill.net/2011-03-04/catching-the-javascript-beforeunload-event-the-cross-browser-way/
Look at the last comment.
Try this:
window.onunload = redirurl;
function redirurl() {
alert('Check this Page');
window.location.href('http://www.google.com');
}

Call Ajax on unload if user clicks "OK"

I'm designing a rather long form that will auto-save every couple minutes (i.e., using Ajax, the form data will be inserted or updated into the MySQL database). However, if the user decides to exit the page before submitting the form, I want to make sure I delete the row that was inserted into the database. This is easily do-able if the user simply clicks another link or the form's Cancel button. But I'm concerned about what happens when the user: 1) closes the page, 2) reloads the page, or 3) hits the browser's back (or forward) button. I know how to use the unload event to create a confirmation dialog asking the user to confirm they want to leave the page. But what I don't know is how to make an Ajax call (to delete that row from the database) if the user clicks OK ("Press OK to Continue"). Is there any way to call a function if a user clicks the OK button during the unload event?
window.onbeforeunload = function() {
if ($('#changes_made').val() == 'yes') //if user (partially) filled out the form
{
return "Are you sure?"
if (/*user clicks OK */) //What should the if statement evaluate here?
{
//make Ajax call
}
}
};
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() {
setConfirmUnload(true);
}); // Prevent accidental navigation away
});
function setConfirmUnload(on) {
// To avoid IE7 and prior jQuery version issues
// we are directly using window.onbeforeunload event
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
if(Confirm('You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.')) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
}
Make sure you have upgraded version of jQuery. jQuery version 1.3.2 had a bug:
Ticket #4418: beforeunload doenst work correctly
Or use native function:
window.onbeforeunload = function() {....}

Categories