user3854236 user3854236 - 1 year ago 112
jQuery Question

Jquery 1.11.1 - download file and additional callback

I have form which i submit to django server by calling.


It server returns xml file by executing this code:

content = some_data_retrieved_from_database_as_xml()
response = HttpResponse(content, content_type='text/xml')
response['Content-Disposition'] = 'attachment; '
response['Content-Disposition'] += 'filename=my_file.xml'
response['Content-Encoding'] = 'UTF-8'
return response

Google Chrome only downloads this file, but i want register additional callback function, called myFunction(data).

Chrome should download this file and next call myFunction(this xml file).

I tried this code, but it doesn't work:

$("#my_form").bind('ajax:complete', myFunction);

I also tried to use $.post, but after that only callback function is called and unfortunatelly my file is NOT downloaded.

Answer Source

So you want to post asynchronously, download the returned file, and also execute a callback. One possibility is to "fake" a download link:

$.post(POST_URL, POST_DATA, function(response) {
  var a = document.createElement('a');
  a.setAttribute('href', 'data:'
    + response.contentType
    + ';charset='
    + response.inputEncoding
    + ','
    + new XMLSerializer().serializeToString(response));
  a.setAttribute('download', DOWNLOAD_FILENAME);;
  // file download triggered

  // additional callback action


As Zoran Majstorovic mentioned in his comment, you can try this jQuery plugin:

Just include the source and then

$.fileDownload(POST_URL, {
  httpMethod: "POST",
  successCallback: myFunction

For security, you need a previously set cookie

Set-Cookie: fileDownload=true; path=/
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download