I have
Click me
What I want to do is take the confirmation box result (true/false), pass it to the submit button, and then kill the href call if its false.
I have it working in my development environment, but when I load this into a cross browser scenario, the second call isn't working:
function submit(msg, evt) {
if(msg == true) {
$.ajax({
type:"POST",
data:{answer:'Correct'},
url:'https://myurl/p'
});
}
else { evt.preventDefault(); return false; }
}
The URL passed is just the URL and has no data to it (in production). This exact code works perfectly fine in my environment, but in the cross browser scenario it fails. If I remove the confirmation box, everything works perfectly.
I have a feeling it's tied to the preventDefault call on the cancel of the confirmation box. Would that preventDefault disable the next call out with that same link?
First of all, please don't use inline event handlers, you can remove this from the markup and deal with it in your js where it belongs:
HTML:
Click me
JS:
anchor = $('#myanchor')[0];
anchor.on('click',function(){
var msg = confirm('Confirm?');
submit(msg, event);
});
Secondly, if msg is true the ajax call is immediately interrupted by a page redirect, which doesn't make much sense. I believe you want the redirect to take place once the ajax call has completed, in which case you should use:
function submit(msg, evt) {
if(msg == true) {
$.ajax({
type:"POST",
data:{answer:'Correct'},
url:'https://myurl/p',
complete: function(){window.location="url";}
});
}
evt.preventDefault();
return false;
}
Click me
$(function(){
$("#myUrlID").click(function(event){
event.preventDefault();
var msg = confirm('Confirm?');
if(msg == true) {
$.ajax({
type:"POST",
data:{answer:'Correct'},
url:'https://myurl/p'
});
}
});
});
Related
I have a settings page with a form. I noticed that people often forget to click the save button, so I decided to send a POST request with $.ajax() on window.onbeforeunload. I'd also like a loader (from Semantic UI) to show before sending the request and hide when it is completed.
This is what I have:
function save(e) {
var msg = 'Your settings were not saved. Please do not leave yet so we can try saving again';
$('form').dimmer('show');
var xhr = $.ajax('settings.php', {type: "POST",
data: $('form').serialize(), async: false});
$('form').dimmer('hide');
if (xhr.status !== 200){
$('form').submit(); //will trigger if the user stays
if (e)
return e.returnValue = msg;
}
}
if ('onbeforeunload' in window)
window.onbeforeunload = save;
else if ('onunload' in window)
window.onunload = save;
else {
var button = $('noscript.submitParent').text();
$('.ui.form.segment').append(button);
}
But now, the loader won't show up until the request is done. I suspect this happens because of async: false, which is necessary so that the page does not unload.
Any suggestions on how to show the loader before sending the request? Is it possible?
I tried $(window).trigger('resize') from here and $('form .dimmer').height() (idea from here), didn't work.
I'm aware of the localStorage alternative, but I'd like not to use it if possible.
I use jQuery 2.1.1
I have a feed that uses AJAX to load in posts once the document is ready. Because the elements aren't ready at code execution, I have to use delegate to bind a lot of functions.
$(posts).delegate('.edit_comment_text','keyup',function(e){
return false;
if (e.keyCode == 13 && e.shiftKey == false) {
//Post the new comment and replace the textbox with a paragraph.
var message_area = $(this).parent('.comment_message');
var new_message = $(this).val();
var comment_id = $(this).closest('.group_comment').attr('data-comment');
var url = 'functions/edit_comment.php';
var array = {
'comment':comment_id,
'message':new_message
}
$.post(url, array, function(data){
console.log(data);
$(message_area).html("");
$(message_area).text(new_message);
});
}
})
This is the code I execute on the event. I've been trying to get the browser to stop dropping down a line when the user hits enter, but this action is performed before my code is even triggered. To prove it, I put the 'return false' at the very top of the block. With that example, none of my code is run when the user hits enter, but the textarea still drops a line.
Is it something to do with JQuery's delegate that causes my function to be called after the default events? They give examples of preventing default events in their documentation, so maybe it's a version bug or something?
Anyone have any ideas?
Thanks!
What I ultimately need to do is run an $.ajax() call and then after that is run, open a new window.
A use clicks on a "Preview" button that saves their current form then opens a new window that shows a preview of the item with the data that was just saved.
But as-is, the window.open function gets blocked by popup blockers.
Here's the basic parts of my code:
HTML:
Preview
JavaScript:
$('.preview').live('click', function(event){
save_survey($(this).attr('href'));
event.preventDefault();
});
function save_survey(url) {
$.ajax({
type: "POST",
url: form_url,
dataType: 'json',
data: form_data,
success: function(data) {
window.open(url, '_blank');
}
});
}
I ran into this problem recently and found this work-around:
1) call window.open just before calling $.ajax and save window reference:
var newWindow = window.open(...);
2) on callback set location property of the saved window reference:
newWindow.location = url;
Maybe it will help you too.
Popup blockers usually works blocking every popup shown not triggered by a direct user action, like clicking on a button or a link.
If you use a ajax request on your click event, the request is fired asyncronous from the click event, that's why by the time the ajax request has done its job and you get your event with the response from the request you have lost your chance to trigger a window.open withouth the popup blocker getting in the way, the original click event it's long dead by that time.
According this this post, it looks like you would have to open your window in direct response to the click (to avoid getting hit by the popup blockers) rather than waiting until the AJAX call completes to open the new window.
I solved my case by making the Ajax call synchronous. E.g. (with jQuery):
$("form").submit(function(e){
e.preventDefault();
$.ajax({
async: false,
url: ...,
data: ...,
success: function(results){
if(results.valid){
window.open(...);
}
}
});
return false;
});
const newWin = window.open(`${BASE_URL}`, 'expampleName')
if (newWin) {
newWin.onload = () => {
const currentOpenWindow = newWin
const href = newWin.location.href
}
}
Hello Seniors (As I am new to Web Based Applications),
I was keen to implement or catching browser closing event.
Yes! I did it and successfully implemented it by using javascript{see code below}
but I have implemented it in a web page without MasterPage.
Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
Is there any technique or logic to detect whether I can differentiate between a Close browser button and a page's post back event.
Please guide me...as I have to implement in a project as soon as possible....
thank you.
Ankit Srivastava
<script type="text/javascript">
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
</script>
<script type="text/javascript">
var g_isPostBack = false;
window.onbeforeunload = check ()
function check()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogOff.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%# Session["loginId"] %>';
var returnCode = callAjax(webUrl, queryString);
}
</script>
There is no javascript event which differentiates between a browser being closed and the user navigating to another page (either via the back/forward button, or clicking a link, or any other navigation method). You can only tell when the current page is being unloaded. Having said that, I'm not sure why you'd even need to know the difference? Sounds like an XY problem to me.
The answer can be found on SO:
How to capture the browser window close event?
jQuery(window).bind("beforeunload", function(){return confirm("Do you really want to close?") })
and to prevent from confirming on submits:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
First step: add global JavaScript variable called "_buttonClicked" which is initially set to false.
Second step: have every button click assign _buttonClicked value to true.. with jQuery it's one line, pure JavaScript is also few lines only.
Third step: in your function check _buttonClicked and if it's true, don't do anything.
EDIT: After quick look in your code I see you already have steps #1 and #3, so all you need is the second step, assign g_isPostBack as true when any submit button is clicked. Let me know if you need help implementing the code and if you can have jQuery.
If one wants to catch Log out when the browser is closed (by clicking on the cross), we can take the help of window events.
Two events will be helpful: onunload and onbeforeunload.
But the problem arises that the code will also work if you are navigating from one page to another as well as also when one
refreshes the page. We don't want our sessions to be clear and inserting the record of logging out while refreshing.
So the solution is if we distinguish the difference between closing and refreshing or navigating.
I got the solution:
Write 'onbeforeunload ="loadOut();"' within the body tag on master page.
Add the following function inside script in head section of master page :-
function loadOut() {
if ((window.event.clientX < 0) || (window.event.clientY < 0))
{
// calling the code behind method for inserting the log out into database
}
}
And its done. It is working for IE, please check for other browsers. Similarly you can detect the event if the window is closed
by pressing the combination of keys ALT+F4.
window.unload fires when we navigate from one page to another as well as when we click on close button of our browser,So to detect only browser close button you need to use flag.
var inFormOrLink;
$("a,:button,:submit").click(function () { inFormOrLink = true; });
$(":text").keydown(function (e) {
if (e.keyCode == 13) {
inFormOrLink = true;
}
})/// Sometime we submit form on pressing enter
$(window).bind("unload", function () {
if (!inFormOrLink) {
$.ajax({
type: 'POST',
async: false,
url: '/Account/Update/'
});
}
})
I have an issue with the following code. What happens is when a user closes their browser, it should prompt them to either click OK or click CANCEL to leave the page. Clicking OK would trigger a window.location to redirect to another page for user tracking (and yes, to avoid flame wars, there is a secondary system in place to assure accurate tracking, in the event of the user killing the browser from the task manager (as mentioned in similar questions)). CANCEL would remain on the page, the issue being that no matter what button you hit, you get redirected as if you wanted to leave the page. The relevant code is below.
window.onbeforeunload = confirmExit;
function confirmExit()
{
var where_to = confirm("Click OK to exit, Click CANCEL to stay.");
if (where_to == true)
{
window.location="logout.php";
}
if (where_to == false){
alert("Returning...");
}
}
The onbeforeunload doesn't work that way. The associated function should return a string which is in turn to be displayed on the default onbeforeunload dialog.
function confirmExit() {
return "This message will appear in the dialog.";
}
But you aren't returning anything and taking it in your own hands with a confirm(). When the function doesn't return anything, then the onbeforeunload dialog won't be displayed at all.
To invoke the real logout, you'd like to use the onunload event. Here's a rewrite:
window.onbeforeunload = confirmExit;
window.onunload = logout;
function confirmExit() {
return "Click OK to exit, Click CANCEL to stay.";
}
function logout() {
window.location = 'logout.php';
}
You're however dependent on the webbrowser whether the last will actually hit the server. Most if not all of the webbrowsers don't. I'd rather fire an ajaxical request on that URL, but you're dependent on the webbrowser as well whether it will work flawlessly.
Perhaps instead of hijacking the user's browser you could fire an XHR request from inside your unbeforeunload() and get the data you need sent over to where you need it?
Without more of the use-case it's hard to tell, but this may provide a nice alternative.
Tested in IE9 and Chrome
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
function exitAlert(e) {
var msg = "This message will appear in the dialog.";
if (!e) { e = window.event; }
if (e) { e.returnValue = msg; }
return msg;
}
addEvent(window, 'beforeunload', exitAlert, false);