0

I have a simple HTML form which sends a simple POST request to a second PHP file:

<form method="POST" action="parse.php">

parse.php generates a file to download and sends it to the output buffer, with the headers

header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Disposition: attachment; filename=test.html");

Can I detect a finished/started download from the form page without using an asynchronous request? Of course I can find out when the form is submitted by onSubmit, but is there a jQuery event fired when the download starts or is finished?

René Roth
  • 1,979
  • 1
  • 18
  • 25
  • If using jQuery ajax or similar call, than use callback function to execute some functions after execution is finished. – Justinas Jul 01 '14 at 09:35
  • 1
    http://stackoverflow.com/questions/2343418/browser-event-when-downloaded-file-is-saved-to-disk I think cookie solution would work for you – eithed Jul 01 '14 at 09:36
  • Thanks for your answers! The cookie solution seems possible. I'm explicitly searching for a non-ajax-solution, if there is one. – René Roth Jul 01 '14 at 09:39
  • Generally you would actually use ajax for things like this to continously poll the server to know when the download finishes, and I think that's the best solution, but PHP sessions can be tricky when doing multiple requests so make sure you clear the sessions etc. – adeneo Jul 01 '14 at 09:41
  • Just to make clear, this is more a theoretical question. Of course I'm using Ajax for this case, but when playing around with my code I started to ask myself this question and couldn't find a straight answer. – René Roth Jul 01 '14 at 11:51

1 Answers1

2

It depends which jQuery method you use.

  • jQuery.post() provides a method called "success" which is called when the post request completes successfully.
  • jQuery.ajax() provides a method called "success" the same as above as well as one called "complete". The complete method is called irrespective of whether it was successful or not.

Further details and examples of their use can be found on the linked jQuery docs.

I have just noticed that the two methods I mention above will be deprecated after jQuery 1.8 and you will be better to use the done() instead of the other ones mentioned. Please see the docs linked above for full details on the usage of both the old and new methods that fulfil your goals.

Example 1 (deprecated):

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function(data){
      // Do something with your data here
  },
  dataType: dataType
});

Example 2:

$.ajax({
  url: "http://example.com/url.php",
  type: 'POST',
  data: data
}).done(function( data ) {
    if ( console && console.log ) {
      console.log( "Sample of data:", data.slice( 0, 100 ) );
    }
});