Edit: I have a solution of sorts, but I do not understand why ajax is not working. Please see the edit below.
- I want to save a txt file generated in javascript to the client machine.
- I want the user to remain on the same webpage.
- I am doing it via ajax with a call to a php page.
- I want it to work in all major pc browsers; Chrome, Firefox, Internet Explorer and Edge.
Here is what I have so far:
htmlsave.js
dataARR = {
SaveFile: "This is the content.\nLine2.\nLine3"
};
var dataJSON = JSON.stringify(dataARR);
$.ajax({
type: "POST",
url: "htmlsave.php",
async: true,
cache: false,
crossDomain: false,
data: { myJson: dataJSON },
success: function (data) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("failure");
}
});
htmlsave.php
<?php
if(!isset($_POST) || !isset($_POST['myJson'])) {
exit(0);
}
$data = json_decode($_POST['myJson'], true);
if(!array_key_exists('SaveFile', $data) || !isset($data['SaveFile'])){
exit(0);
}
$contents = strval($data['SaveFile']);
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"mysavefile.txt\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . strlen($contents));
ob_clean();
flush();
echo $contents;
?>
What comes back (ie the data argument in success) is "This is the content.\nLine2.\nLine3".
There is no prompt to save the file with content "This is the content.\nLine2.\nLine3" as I had hoped.
Edit: A solution (but not a great one)
I have done a bit of tinkering and have something that works, in a fashion. Instead of calling through ajax I write in my javascript
document.location = "htmlsave.php?myJson=Line1Line2";
and in my php I have altered it to a get with
if(!isset($_GET) || !isset($_GET['myJson'])) {
exit(0);
}
$contents = $_GET['myJson'];
This works. This will be ok for small files, but I wanted to do reasonably large text files, and even zipped using lzw encoding. Anyone know why Ajax is not working?