tags:

views:

41

answers:

2

Hi,

I wanted to let a user download a file by simply clicking a button. Thing is, the file doesn't actually exist - its just some dynamic content.

So lets say:

$('a.download').click(function(){

$.post('get.php');
})

and in my PHP:

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=something.txt");
header("Content-Type: text");
header("Content-Transfer-Encoding: binary");
echo 'abcbdefg'

Is that valid? Is there some other way to do it?

A: 

Yeah, that's valid. I'm pretty that's the best way to do it.

stormdrain
+1  A: 

Just create a link to the file, like this:

<a href="get.php">download my file</a>

Whenever there's a request for a file of type PHP, your webserver will first process the file and output whatever text it contains to the client; you don't have to do anything special just because it's dynamic.

Using $.post() doesn't make sense for what you want to do; that POSTs data to the url you specify, it doesn't prompt the user to save a file.

Faisal
I've simplified. I also need to POST some data, depending on which the output is generated.
Rohan
Unfortunately, jQuery's $.post() function isn't going to make your browser prompt the user to download a file -- you have to redirect the browser to 'get.php' rather than performing an AJAX request for it. You could perhaps create a form element with its action as 'get.php' and trigger a submit() on it...
Faisal
I guess that would work, thanks :-)
Rohan