Skip to content Skip to sidebar Skip to footer

Force Download After Ajax Call

I have a php script that is waiting for ajax calls at www.mydomain.com/file.php The ajax call contains some variables, that the file.php will use to generate some csv results, Woul

Solution 1:

Sure, in the PHP file before you output anything, set the content-type to something the browser will download:

header("Content-Type: application/octet-stream");

Additionally this is a good practice to include too (and lets you suggest a file name):

header("Content-Disposition: attachment; filename=somefile.csv;");

Depending on the browser sometimes only the later is needed, but I generally use both to make sure.

Solution 2:

Putting elements in a form and submitting them just seems to hacky, and I don't feel comfortable using it.

When you are using these types of things I think you are risking a bit, the next versions of browsers may simply not support them.

Besides I am passing complicated arrays as options in my ajax call to the server, and it's not easy to convert them all into an html form, unless I serialize the arrays in a hidden element and unserialize it on the server side, but that's all too complex.

What I did instead was, when the ajax call is made, the server stores the output in a session, then it returns a unique key for that value, another page on the server will simply echo the output when that key is given to it as an input,

So user clicks on something, then an ajax call is made, then the server stores that in a session, then user clicks on a download link and then the server removes that session.

It may not be the most perfect solution specially since the user has to click twice, but it just seems more standard to me.

Solution 3:

@user893730- Why is putting elements in a form and submitting them "hacky?" Also, I don't see why serializing and deserializing array data is "complicated"--there are a billion libraries out there that support precisely that sort of thing.

Post a Comment for "Force Download After Ajax Call"