JQuery 1.11.1 - download file and optional callback

I have a form that I submit to the django server by calling.

$("#my_form").submit(); 

The server returns the 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 need an extra callback function called myFunction (data).

Chrome should load this file and the next call to myFunction (this xml file).
I tried this code but it does not work:

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

I also tried using $ .post, but after that only the callback function is called and, unfortunately, my file is NOT uploaded.

+7
javascript jquery file django download
source share
4 answers

So you want to post asynchronously, load the returned file and execute a callback. One possibility is to "fake" the 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); a.click(); // file download triggered myFunction(); // additional callback action }); 

Update

Like Zoran Maystorovich mentioned in his comment, you can try this jQuery plugin: http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

Just turn on the source and then

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

For security, you will need a previously set cookie.

 Set-Cookie: fileDownload=true; path=/ 
+1
source share

$ (form) .submit () is not ajax, but submits a form (usually POST), so you cannot register an event listener to send an "AFAIK" response. I am using cookie - based jquery-file-download-plugin to execute some javascript as you need.

0
source share

I believe in the answer, at least according to this similar topic:

How to execute jquery callback after form submission?

:

 $("#myform").bind('ajax:complete', function() { // tasks to do }); 

See jQuery documentation for ajaxComplete

0
source share

A simple way is that the result of the submission will be an html page with an iframe . iframe will do the loading and the parent html will do whatever you like.

0
source share

All Articles