J Mint J Mint - 5 months ago 29
Ajax Question

ajax/php file download not working?

I am trying to force download a txt file upon clicking on a button. The content is dynamically generated and is stored in a javascript variable. The download window doesn't appear when clicking the button however the ajax call is successful. What am I doing wrong?

The php:

$Proof = $_REQUEST["Proof"];
$proof = stripslashes($Proof);
$file = 'savedproof.txt';
file_put_contents($file, $proof);
header('Content-disposition: attachment; filename="'.$file.'"');
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header('Content-Description: File Transfer');


The javascript:

$("#save").click(function () {

var proof = $("#main").html();
type: 'POST',
url: 'save-to-file.php',
data: {Proof: Proof},
dataType: "html"


Alternatively I tried using window.location.href but I couldn't pass the variable Proof to the php file.
I tried something like this:

window.location.href ="download.php?Proof="+Proof;

Although the download dialog does appear, only the beginning part of the variable Proof is in the file.
I tested both ways on firefox and chrome.


Your AJAX request isn't working because it isn't triggering browser navigation. It's just feeding the response to Javascript, which is ignoring it. You'll probably need to construct a fake <form> element and submit it to get the results to download.

As far as window.location.href is concerned, URLs are typically limited to about 2 to 4 KB, so you're getting cut off. So that won't work.