0

I want to make an AJAX call to PHP function that creates a txt file and download it.

 if (isset($_POST["download_file"]))
{
    $filename = "sequence.txt";
    $f = fopen($filename, 'w');
    $content="q";
    fwrite($f, $content);
    fclose($f);
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Length: ". filesize("$filename").";");
    header("Content-Disposition: attachment; filename=$filename");
    header("Content-Type: application/octet-stream; "); 
    header("Content-Transfer-Encoding: binary");
    readfile($filename);
}

This is my PHP code and here is AJAX code

$.ajax(
{
        url:"./apis/download_seq.php",
        data:{download_file:"true",sequence:seq},
        type: 'POST',
        success:function(data){
        }
});

And this is AJAX call. Problem is that my current code saves file on server. Like it create sequence.txt file in directory where my PHP file is located. I want to download it to client side i.e. to my browser.

Zia ur Rehman
  • 331
  • 1
  • 2
  • 20

1 Answers1

1

I am a little out from PHP but something like that for PHP side:

This part could be skipped:

$f = fopen($filename, 'w');
$content="q";
fwrite($f, $content);
fclose($f);

And if file is not huge, you can replace that with simple variable:

$text = "q";
$text = $text."new text";

At the end:

readfile($filename);

Replace with:

echo($text);

I DID NOT TEST THIS :) so make a test.

For Jquery part there is a lot of answers there: Download File Using Javascript/jQuery

Community
  • 1
  • 1
Danijel
  • 817
  • 1
  • 17
  • 31