window.onbeforeunload = function() {
return $j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
this what I have, but it returns an alert with [object Object]
how do I just execute the AJAX?
note: when I just don't return anything, the server doesn't show that it is receiving the ajax request.
You don't need to return anything, just fire the ajax call.
window.onbeforeunload = function(e) {
e.preventDefault();
$j.ajax({ url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + &time_on_page=" + getSeconds()
});
}
If you are using jQuery, you can try binding to the .unload() event instead.
onbeforeunload allows you to return a string, which is shown in the 'Do you want to leave' confirmation. If you return nothing, the page is exited as normal. In your case, you return the jqXHR object that is returned by the JQuery ajax method.
You should just execute the Ajax call and return nothing.
Why are you returning the reference of function to global pool? It should be like this:
window.onbeforeunload = function() {
$j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
To the best of my understanding, the onbeforeunload function will only return an alert. This was done to prevent the annoying popups of a few years back.
I was building a chat client a while back and the only way i could figure out to do something like this is to do a setInterval function that updated a timestamp, then checked for timed out users and removed them. That way users that didnt "check in" within a certain interval would be removed from the room by other users still logged in.
Not pretty, or ideal, but did the trick.
Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page).
In the rare case when you need to send information as the user is navigating away from the page (as Aaron says, avoid this where possibl), you can do it with sendBeacon. sendBeacon lets you send data to your server without holding up the page you're doing it in:
window.addEventListener("unload", function() {
navigator.sendBeacon("/log", yourDataHere);
});
The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).
Note that the unload event may not be reliable, particularly on mobile devices. You might combine the above with sending a beacon on visibilitychange as well.
Related
Working on a platform, to enable auto-ticketing functionality. For which a REST API request is used for ticket creation. Unfortunately, there are 2 requests popping simultaneously, which results in creating duplicated tickets.
How to handle such case and send only one of these requests?
Tried adding the 2nd request in the response callback of the first, though this does not seem to work.
if (flag == 1){
logger.debug("Node-down alarm-Request raised - +sitn_id);
clearTimeout(mouseoverTimer);
mouseoverTimer = setTimeout(function(){
logger.debug("Inside Call back function - ");
//function call for ticket creation
incidentRequest(sitn_id,confUtil.config.mule_url);
}, 10);
You really should show more of the code that makes the request, though it seems as if you are doing some ajax inside your 'incidentRequest', so I will presume that (if that isn't what you are doing, then please, show your code....) - and since you tags say javascript and jquery - well, here goes...
To stop the 'double send' in an AJAX call, it is simple:
function incidentRequest(sitn_id,confUtil.config.mule_url){
// stop the double by clearing the cache
$.ajaxSetup({cache: false});
// continue on with the AJAX call
// presuming the url you want is confUtil.config.mule_url
// and the data you want to send is sitn_id
$.post(confUtil.config.mule_url, 'sitn_id=' + sitn_id, function (data) {
// do cool stuff
});
}
Hopefully that will help you get moving. If not, then we will need more code of what is going on around all this.
I am triggering a change event in my casperJS script which triggers an AJAX request like such:
casper.evaluate(function(i) {
$("form:eq(2) select option:eq(" + i + ")").attr("selected", "selected").change();
},i);
How can I make casperJS wait until the underlying AJAX request has been finished? Already tried to look at the docs but I am more or less stuck. Can anyone guide me into the right direction?
You can always do this in a static way using casper.wait.
casper.thenEvaluate(function(i) {
// change()
},i).wait(5000).then(function(){
// further processing
});
And hope that the request is done in 5 seconds, but maybe you lose some time waiting when the request is done much sooner than 5 seconds. The problem is that as soon as the request is finished doesn't mean that the page is ready/changed.
Another possibility would be to wait for the request to finish, but for this to work you will need to register for the success event of the request somehow. Most of the time you don't have access to this from the global scope. If you do then you can use
casper.thenEvaluate(function(i) {
window._someUniqueVariable = false;
registerSuccessEvent(function(data){
window._someUniqueVariable = true;
});
},i).waitFor(function check(){
return this.evaluate(function(){
window._someUniqueVariable = true;
});
}, function(){
// further processing
});
A more Casper-way of doing that would be to use casper.waitForResource, but then you would need to know the url beforehand or at least able to deduce it from the page.
In the general case, when the request comes back it does something to your page. So you should be able to waitForSelector with a new element or waitForSelectorTextChange or waitUntilVisible etc.
you probably missed waitForResource
from the docs: http://casperjs.readthedocs.org/en/latest/modules/casper.html#waitforresource
casper.waitForResource("you url here", function()
{
// place your code here
});
Hi i have to perform perform like, when the ajax is in progress, then do not allow the user to do page refresh.
here is the code i have
$('#submit').click(function() {
$(function() {
$(".col1").mask("Generating csv...."); //This will generate a mark, Here i would like to prevent the user from doing any sort of operation.
var to = $('#filters_date_to').val();
var from = $('#filters_date_from').val();
$.ajax({
url:"../dailyTrade/createCsv?filters[date][to]="+to+"&filters[date][from]="+from,success:function(result){
if(result) {
$(".col1").unmask(); //Here we can unlock the user from using the refresh button.
window.location = '../dailyTrade/forceDownload?file='+result;
setTimeout('location.reload(true);',5000);
}
}
});
});
});
Any suggestions.
Best you can do is use onbeforeunload to present the user with a message saying that a request is in progress and asking them if they are sure they want to proceed.
e.g.
var req;
window.onbeforeunload = function() {
if(req) {
return 'Request in progress....are you sure you want to continue?';
}
};
//at some point in your code
req = //your request...
You cannot, in any way, prevent the user from leaving your page using JS or anything else.
I doubt if you should do that.
$(window).bind('beforeunload',function(){
return 'are you sure you want to leave?';
});
If you are talking about a refresh "html button" on your web page, that can easily be done. Just before you make your ajax call, disable your refresh button and on success/error function of the ajax call enable it.
Disable button
$("#refreshBtn").attr("disabled", "disabled");
Enable button
$("#refreshBtn").removeAttr("disabled");
You cannot do it just by inserting JavaScript code.
Only ways I can think of are:
Use synchronous ajax call, on that way browser should freeze (however it will notify user that script is taking too long to process and user will be able to stop execution)
Write browser plugin that will modify browser behavior (eg. prevent refreshing page for url that you preset)
Both ways are ugly and I wouldn't recommend doing it.
You should modify your script so it can resume execution if page has been refreshed (use HTML5 localStorage).
http://www.w3schools.com/html/html5_webstorage.asp
In your case, I would put in localStorage simple state (boolean) to check did ajax call happened or not. If it did happened, then just try calling again same url and you will get file name. But on server side (if you haven't done already) you should implement caching, so when same url is called twice, you don't need to make two separate files, it could be same file (server will be much lighter on hardware resources).
Is it bad practice to perform a redirection within an jQuery AJAX request?
$.ajax({
url: "myurl",
success : function(response) {
window.location.replace('MYNEWPAGE');
},
error: function (xhr) {
}
I'm experiencing some strange behaviour in an app and I think this is the issue.
location.replace() doesn't store the current page into the browser history, the user can't use the back button to go back onto the page. You should use location.assign(URL) or location.href = URL.
Should only use window.location.href = "whatever" to change the url. Note that this will cause you to postback your whole page, strange behavior may come from your load events on new page firing unexpectedly, including other ajax events that might also set window.location.href - you could theoretically get deadlock with stuff just continuing to send you to new pages (careful).
I'm working on a chat and I'm trying to figure out how I can detect that the user has left the page or not. Almost everything is being handled by the database to avoid the front end from messing up.
So what I'm trying to do is once the page is left for any reason (window closed, going to another page, clicking a link, etc.) an ajax call will be fired before a person leaves so I can update the database.
This is what I've tried:
$(window).unload(function(){
$.post("script.php",{key_leave:"289583002"});
});
For some odd reason, it wouldn't work, and I've checked the php code, and it works fine. Any suggestions?
Try this:
$(window).unload(function(){
$.ajax({
type: 'POST',
url: 'script.php',
async:false,
data: {key_leave:"289583002"}
});
});
Note the async:false, that way the browser waits for the request to finish.
Using $.post is asynchronous, so the request may not be quick enough before the browser stops executing the script.
This isn't the correct way of doing this... Suppose the OS just hangs or something happens in the browsers process then this event wont be fired. And you will never ever know when the user has left, showing him/her online ever after he/she has disconnected. Instead of this, what you can do is.
Try connecting a socket so that you can know the user is disconnected when the socket is disconnected
You can send a request to the server (say after every 1 sec) so that you can know that the user is still connected. If you didn't receive the request - even after 2 secconds - disconnect the user.
Try to add popup (prompt("leaving so early?")) after $.post. It may work. Tho it may be bad user experience. :)
This is related to the answer above. https://stackoverflow.com/a/10272651/1306144
This will execute the ajax call every 1 sec. (1000)
function callEveryOneSec() {
$jx.ajax({}); // your ajax call
}
setInterval(callEveryOneSec, 1000);
The unload event is not recommended to detect users leaving the page. From MDN:
Developers should avoid using the unload event ... Especially on mobile, the unload event is not reliably fired.
Instead, use the visibilitychange event on document and/or the pagehide event on window (see links for details). For example:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
$.ajax({
type: 'POST',
url: 'script.php',
async:false,
data: {key_leave: "289583002"}
});
}
});
Better yet, use Navigator.sendBeacon, which is specifically designed for the purpose of sending a small amount of analytics data to a server:
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
navigator.sendBeacon('script.php', {key_leave: "289583002"});
}
});