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.

1
  • 1
    So echo instead of write. Remember to set the content-type Commented Mar 14, 2015 at 8:55

1 Answer 1

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

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

Comments

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.