Created
August 30, 2012 17:03
-
-
Save DavidMah/3533415 to your computer and use it in GitHub Desktop.
File Download requests using jquery/POST request with psuedo ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Takes a URL, param name, and data string | |
// Sends to the server.. The server can respond with binary data to download | |
jQuery.download = function(url, key, data){ | |
// Build a form | |
var form = $('<form></form>').attr('action', url).attr('method', 'post'); | |
// Add the one key/value | |
form.append($("<input></input>").attr('type', 'hidden').attr('name', key).attr('value', data)); | |
//send request | |
form.appendTo('body').submit().remove(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A Tidbit of sinatra code to respond | |
# Assume url is a set variable | |
# Assume 'key' is the key of the value used in the javascript | |
post url do | |
data = params[:key] | |
puts request.body.read | |
headers['Content-Type'] = "application/octet-stream" | |
body(data) | |
end |
Here is a more readable coffeescript version :)
attrs = { action: '/target-path.csv', method: 'post', target: '_blank' }
params = { key1: 'value1', key2: 'value2' }
form = $('<form></form>').attr(k, v) for k, v of attrs
form.append $('<input></input>').attr('type', 'hidden').attr('name', k).attr('value', v) for k, v of params
form.appendTo('body').submit().remove()
Server returned error #400.
I have more than two files to be downloaded at the page. If I click at one file and click the next one before the first download is completed only second file gets downloaded and first one is failing. Please let me know if someone of you have resolved this issue.
Just found today a very simple solution
window.location.href = 'urltofile';
Thanks, man, you saved the day!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
π₯ Thanks a lot @DavidMah π
Even if it's not working for my part π
Are the key and data attributes essential if I remove the "input" line (line 8) ? It only redirects me.
EDIT: Sorry, I think it is my fault. Not sure yet
EDIT2: Okay, My problem is now solved Thanks again π