简体   繁体   中英

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:

<?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');

readfile($file);
?>

The javascript:

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

    var proof = $("#main").html();
     $.ajax({ 
             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.

Javascript can't download files to the client machine due to security concerns.

Just make the button a link (styled however you want) and do this:

<a id="save" href='/path/to/download.php' target="_blank"></a>

Then have an onready function to change the href based on the the value of #main

$.ready(
   var proof = $('#main').html();
   var href = $('#save').attr('href') + '?Proof=' + encodeURIComponent(proof);
   $('#save').attr('href', $href); 
});

No reason for AJAX at all here as far as I can tell.

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.

You can do this by creating and sending form via jquery (page not reloaded):

$(document).on('click', '#save', function () {
    var proof = $("#main").html();
    var form = $(document.createElement('form'));
    form.attr('action', 'save-to-file.php');
    form.attr('method', 'POST');
    var input = $('<input>').attr('type', 'hidden').attr('name', 'Proof').val(proof);
    form.append(input);
    form.appendTo(document.body);
    form.submit();
    form.remove();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM