I created a PHP file which forces a file download.
When I call it via ajax it won’t work.
Google says ajax can’t handle downloads.
I should just open a new window directing to the url.
The problem is the file does only exists while the php script is running.
So how do I get around this problem ?
Here is the code:
PHP:
<?php
$jsonStr = $_POST['jsonStr'];
$tmp_file = tempnam('/tmp', 'data-');
$handle = fopen($tmp_file, 'a+');
fwrite($handle, $jsonStr);
if(!$tmp_file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=iwbtg.lvl");
header("Content-Type: text/plain");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($tmp_file);
}
?>
JS:
...
var jsonStr = JSON.stringify(jsonObj);
// Request Level file
var http = createRequestObject();
http.open("POST", "save.php", false);
http.setRequestHeader("Content-Type", "application/x-www.form-urlencoded");
http.send("jsonStr=" + jsonStr);
document.location = "tmp/iwbtg.lvl";
Instead of ajax you could use an iframe. This is not pretty but works well. You do the post to the iframe and that will not reload the whole page which is what i guess you are trying to avoid in the first place.