I would like doing in javascript (jQuery):
if (close tab || close window) {
$.ajax({
type: "POST",
url: "process_form.php",
data: dataString
});
}
Is this possible without message if you want leave page etc?
There is only one useful event you can rely on for that reason, onbeforeunload.
window.onbeforeunload = function() {
$.ajax({});
};
Unless you explicitly return false from that event, there is no message to the user. You might want to create a synchronised request anyway, because the browser will not wait for an asyncronous request to finish.
Related
I have a js function, when I give async as false it opens as new
window,
but when i give async as true its showing as pop up
I need to make the code as async as true, but it should open as new
window not as pop up
can you guys tell me how to Make a asynchronous request so that the
new window willnot load as a popup.
is there any alternate method for window.open
providing my code below
//
debugger;
Ext.Ajax.request({
async: false,
url: sports.util.Utils.getContextPath() + '/tabClicks.do',
Your code is a little bit weird so it's hard to make the adjustment properly but this is gist of it:
showNewWindow: function(menu) {
var me = this,
newWindowId = sports.util.Utils.randomString(12);
//
// Make a synchronous request so that the new window will
// not load as a popup.
//
debugger;
var popup = sports.util.Utils.openNewWindow('', 'menu', {}, null, null, newWindowId);
Ext.Ajax.request({
async: false,
url: sports.util.Utils.getContextPath() + '/tabClicks.do',
params: {
oldWindowId: sports.util.Utils.getWindowName(),
newWindowId: newWindowId
},
success: function() {
popup.location.href = "/desktop/main";
},
scope: me
});
},
Popup blockers try to tell when a window is being opened in direct response to a user action or spontaneously by the application. The way they probably do this is by checking whether the function that called window.open() was run in response to a user-triggered event like a mouse click.
When you perform a synchronous AJAX request, the function that was triggered by the mouse click is still running when the response arrives and the success function calls window.open. So it's considered to be a user-requested window, not a popup.
When you use asynchronous AJAX, the click handler is no longer running when the success function runs. The asynchronous call to window.open is considered spontaneous by the browser, so it blocks it.
I don't think there's any way around this, because anything you could do could also be used by everyone else to get around popup blockers, and they would be useless.
function openNewWin(name) {
$.ajax({
async: false,
type: 'POST',
url: 'your url',
success: function () {
window.open(name);
},
async: false
});
}
I have a page where I show 5 questions to a user and when he clicks on Next 5 link I am sending the score of current page onbeforeunload() to the script updateScore() asynchronously using jQuery AJAX and when the call is successful the next 5 questions are displayed.
window.onbeforeunload=function()
{
$.ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
cache: false,
timeout:5000,
async:false
});
}
But the problem is that on slow connections,it might hang the browser for a while until AJAX call returns successfully.When I tried async:true(default) the next page is loaded first without making call to updateScore.php.It might be due to the fact that connection is fast in localhost hence giving no time for the AJAX call to complete.This was the reason I used async:false.Will it happen (making no AJAX call) if I use async:true in practical case as well?If yes, is there a way to come around this problem?
I advice you to change your code a bit.
Make ajax request on "click" event, and redirect user inside ajax callback function.
Like this:
$('#mybutton').on('click', function()
{
$('#pleasewait').show();
$ajax({
type: "POST",
url: "updateScore.php",
data: "pageScore="+score,
success: function() { document.location="nextpage.php" }
});
}
I use onbeforeunload to reset a variable with Ajax request. But it is executed once only. E.g if I visit the page (after log in) and close the window, the function is executed, but if I repeat the operation (putting the address in the browser with login done and closing the window) the function isn't executed.
window.onbeforeunload = function (e) {
//Ajax request to reset variable in database
resetDemoValueWithAjax();
};
//Ajax request to reset variable in database and exit
function resetDemoValueWithAjax(){
$.ajax({
async:true,
type: "POST",
dataType: "json",
url:"http://localhost/site/index.php/welcome/resetDemoValue",
data: {name: "demo"},
success:function(){
document.location.href='http://localhost/site/index.php/auth/logout';
},
error: function(){
document.location.href='http://localhost/site/index.php/auth/logout';
}
});
}
document.location.href='http://localhost/site/index.php/auth/logout'; Only is used in another moment: When the user does logout. Not here
You have a race condition. The race is between the asynchronous Ajax request and the browser's attempt to navigate away from the page (which is what caused beforeunload in the first place). The navigation away will probably always win, so the browser moves away from the page before the Ajax callback can complete.
If you made the Ajax request synchronous with async:false, this race wouldn't happen, since the JavaScript thread would block until the Ajax request resolved. Be aware that this makes for a potentially annoying user experience (i.e., the user tries to close the page but has to wait for the Ajax request to resolve before the tab will close).
I have this function to unlock a list the user is currently editing:
function unsetLock(id) {
$.ajax({
type: "POST",
url: "/ajax.php?action=unsetLock",
dataType: 'json',
data: "id="+ id
});
return true;
}
When the user navigates away from the list, I have to cancel the lock:
unsetLock(lockID);
document.location.href='/page/to/navigate/back/to.php';
However this unlock sometimes works and sometimes doesn't. I think it is because document.location.href is executed, before the ajax call has actually been sent to the server.
How can I force to send the unlock before navigating the user to the next page?
Actually I don't need to wait for the Ajax-Reply, since I want to redirect the user, whether it succeeds, or not. I just want to make sure, it is being transferred to the server.
If I place the document.location.href inside the Ajax function, it will wait for the reply.
A really bad-mannered way to do it is to add: async: false, which will lock the browser up until the AJAX call is complete.
Of course, if there is a problem and the AJAX call never completes...
It's the quickest and easiest solution to your problem, but probably not the best.
I, personally, would have the lock only last for twenty seconds (using a timestamp in the database), and send an ajax call every ten seconds to re-lock the page (if that makes sense) using setInterval().
That way the lock will unset itself a few seconds after someone leaves the page, and is good no matter what the situation (a power failure for the client wouldn't leave the page locked forever, for example).
Perhaps I'm missing something, but why not use the success option in the Ajax call? This will execute whatever the outcome and makes sure it reaches the server.
function unsetLock(id) {
$.ajax({
type: "POST",
url: "/ajax.php?action=unsetLock",
dataType: 'json',
data: "id="+ id,
success: function(){
document.location.href='/page/to/navigate/back/to.php';
}
});
return true;
}
I need for a php file to process when the user click a link/go back/exits a page. Its part of a saving user info process. if i do a jquery unload how would I fire the php file to load and process.
jQuery(window).bind("unload", function() {
// what should i add?
});
$(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() {....}
I'm guessing a synchronous AJAX call might work.
$.ajax({
async: true,
url: '/foo/',
success: function(data) {
// Finished.
}
});
Of course, keep in mind there's no guarantee any of this will ever happen. My browser may crash. My computer may even power down. And of course I may disable JavaScript. So you'll definitely need a server-side way of handling this in case the convenient JavaScript technique doesn't actually work.
You should use the beforeunload event. You can fire a synchronised ajax request in there.
$(window).bind('beforeunload', function() {
$.ajax({
url: 'foo',
async: false,
// ...
});
});
Be aware that onbeforeunload is not supported by some older browsers. Even if this technique works, I'm not sure how long you can (should?) block this event. Would be a pretty bad user experience if that request would block a few seconds.
A good trade-off is probably to tell the user that something has changed what was not saved yet. Do this with a few boolean checks and finally return a string value in the onbeforeunload request. The browser will then gracefully ask the user if he really wants to leave your site, also showing the string you provided.