popClingwrap
popClingwrap

Reputation: 4217

Save Javascript string to .TXT file with PHP

Sorry if this is a little rambling and takes in a few subjects. I will try to keep it straightforward and say off the bat that I am new to JS, jQuery and PHP :)

I have some JS that generates a string and I want to save this string in a plain text (.txt) file to the users local machine.

I have a PHP file set up that simply does this:

header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="testFile.txt"');
echo "Saved Data";

If I navigate straight to this page then I get testFile.txt appear in my Downloads folder. All good so far so I tried to send my string from the JS using:

$.post("_php/writeFile.php",
{
    data:"Test Data"
},
function(data, status)
{
    alert("Data: " + data + "\nStatus: " + status);
});

Now when I run this the alert fires and reads the 'Saved Data' string so I assume the PHP is getting reached but the download does not trigger.

If anyone can explain whats going on here for my own education that would be great. If you can suggest how to get it working then that would be even better for my sanity :)

Cheers all.

Upvotes: 0

Views: 320

Answers (1)

Peter Herdenborg
Peter Herdenborg

Reputation: 5962

Downloading a file can't be triggered by an ajax request. You will have to either use a GET request instead, navigating to the actual url, like window.location.href = '_php/writeFile.php', or submit a form with the same URL as its action.

Upvotes: 4

Related Questions