René Roth
René Roth

Reputation: 2116

Detecting start and stop of synchronous POST request

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?

Upvotes: 0

Views: 94

Answers (1)

SpikeyFruit
SpikeyFruit

Reputation: 21

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 ) );
    }
});

Upvotes: 2

Related Questions