3

Is there a way to detect when the user has clicked the stop button on any browser? I want to stop the script from running when the user decides to click the stop button when uploading a file, so I can trigger the script to refresh the page.

user1105430
  • 1,249
  • 3
  • 13
  • 23
  • may be you can set the timmer and check if dom is not loaded after a time limit you can stop you js – Shoaib Shaikh Jun 27 '12 at 06:40
  • Everyone's bandwith and filesize is different. I would actually interrupt the upload if I do that. – user1105430 Jun 27 '12 at 06:52
  • so you want to stop js that is running while you upload file to server? or you want to stop js if user stops the page before it is loaded completely? – Shoaib Shaikh Jun 27 '12 at 06:54
  • stop js if user stops the page before it is loaded completely – user1105430 Jun 27 '12 at 06:56
  • 1
    why don't you do this other way around to start your js when dom is loaded? – Shoaib Shaikh Jun 27 '12 at 07:04
  • wrap it in a $(function(){}); that way it will only load if the page is ready – Patsy Issa Jun 27 '12 at 07:35
  • The js function is initiated on file submit, but how do I stop it when interrupted? Try it out. when you submit a file to upload the dom doesn't change or reload. The server reacts on file submit but the dom stays the same until the file has finished uploading. I don't think its possible without another extension such as 'APC' or 'uploadprogress' module. – user1105430 Jun 27 '12 at 18:53

1 Answers1

1

Unfortunately the browser's stop button doesn't affect AJAX requests. If you want to cancel an AJAX request you can abort it like below:

var xhr = $.ajax(
    url: "http://someurl.org",
    success: function() { ... }
);

xhr.abort();

The button to trigger the abort will need to be in your HTML since the browser's stop button cannot abort the request. If the user went to another page the browser would stop listening though and this is essentially what happens when you call xhr.abort().

John Culviner
  • 19,634
  • 5
  • 47
  • 47
  • I wonder, is there a way for the php script to detect the upload has been cancelled so I can redirect the page? I don't think it's possible then. – user1105430 Jun 27 '12 at 06:43
  • It primarily doesn't have to be about AJAX. For an instance, when the browser's stop button has been clicked alert('Your upload has stopped'); and then refresh the page afterwards. Refreshing the page will stop the AJAX anyways. – user1105430 Jun 27 '12 at 06:49
  • Unfortunately the server will have no idea the request has been cancelled and it will fulfill the life of the request and perhaps even generating a response to a browser that isn't listening anymore. If you need to allow for a redirect after a user cancels just know the location ahead of time and do a window.location = 'newUrl' with JavaScript – John Culviner Jun 27 '12 at 06:49