Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  101] [ 7]  / answers: 1 / hits: 61256  / 14 Years ago, wed, february 9, 2011, 12:00:00

I have a web page that handles remote control of a machine through Ajax. When user navigate away from the page, I'd like to automatically disconnect from the machine. So here is the code:



window.onbeforeunload = function () {
bas_disconnect_only();
}


The disconnection function simply send a HTTP GET request to a PHP server side script, which does the actual work of disconnecting:



function bas_disconnect_only () {
var xhr = bas_send_request(req=10, function () {
});
}


This works fine in FireFox. But with Chrome, the ajax request is not sent at all. There is a unacceptable workaround: adding alert to the callback function:



function bas_disconnect_only () {
var xhr = bas_send_request(req=10, function () {
alert(You're been automatically disconnected.);
});
}


After adding the alert call, the request would be sent successfully. But as you can see, it's not really a work around at all.



Could somebody tell me if this is achievable with Chrome? What I'm doing looks completely legit to me.



Thanks,


More From » ajax

 Answers
12

I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.



I was only able to get it to work if the request was synchronous. I was able to do this with Jquery and setting the async property to false:



$(window).unload(function () {
$.ajax({
type: 'GET',
async: false,
url: 'SomeUrl.com?id=123'
});
});


The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.


[#93817] Tuesday, February 8, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;