0

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Um - if the OP had readFile.php (the first one), and writeFile.php (for saving the data, to which the ajax request is done), I think window.location.href = readFile.php would suffice inside the callback.
If you are triggering a download without navigating away from the page, create a dynamic link for the user to click on, which triggers the PHP page. This bypasses popup blockers. If you are downloading on the same page, you might as well reload the page with the PHP page directly, either via a GET or form POST.
So is there no way that I trigger the download without navigating away from the original page? Sorry if this is a daft response, I'm the first to admit there are massive gaps in my knowledge here.
@popClingwrap, well, since this "navigating away" merely results in a download prompt, you don't actually leave the current page, but it will remain in the browser once the file has been saved.
Awesome, got it working. I set up a form with a hidden input then set the value of this input dynamically to be my JS generated string before submitting it. Seems to be doing the job nicely. Thank you all for your comments, I learned something today :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.