Nathan
Nathan

Reputation: 3165

Forcing a file to download via JQuery

I have a textarea that accepts a bunch of data. I then submit it via $.ajax to a PHP script that processes it and generates a KML.

var pData = $("textarea#data").serialize();
$.ajax(
{
    type: "POST",
    url: "tools.php?mode=process",
    data: pData,
    success: function(data)
    {
        window.location.href = "tools.php?mode=download&"+pData;
    });
});

This did work fine, until I started getting more and more data. Now I get a URI Too Large error, and am trying to find an alternative to force a file download. I tried using $.post() as well, but I can't force it to download.

Upvotes: 0

Views: 10356

Answers (2)

Ryan
Ryan

Reputation: 81

The best way I found to save data to a file and then force download it with jQuery, create your file and save the data with PHP:

       $data = ''; // data passed to a function or via $_POST['data']
       $targetFolder = $_SERVER['DOCUMENT_ROOT'] . '/location/of/file/'; 
       $savedFile = $targetFolder . md5($data). '.html';
       $handle = fopen($savedFile, 'w') or die('Cannot open file: '.$savedFile);
       fwrite($handle, $data); 

       if(file_exists($savedFile)) {
            $fileName = basename($savedFile);
            $fileSize = filesize($savedFile);

            // Output headers.
            header("Cache-Control: private");
            header("Content-Type: application/stream");
            header("Content-Length: ".$fileSize);
            header("Content-Disposition: attachment; filename=".$fileName);

            // Output file.
            readfile ($savedFile);                   
            exit();
        }
        else {
            die('The provided file path: ' . $savedFile .' is not valid.');
        }  

Use jquery on a .click function or $.post

var forceDownload_URL = 'your/download/function/url.php';

$('#download').click(function(){
     window.open(forceDownload_URL);
});

// Post method untested, but writing on the fly when called as above works well
// getting your forceDownload php to return the absolute path to your file
$.post(forceDownload_URL,{postdata:my_data},function(data){
    window.open(data);
});

Upvotes: 3

Pekka
Pekka

Reputation: 449425

Following up the discussion in the comments, the optimal workflow for this might be

  1. data gets sent to mode=process through Ajax and POST;
  2. script saves result in a temporary file (with a random name) and returns the name of that file in the AJAX response body
  3. location.href call goes to mode=download and the name of the temporary file
  4. script opens temporary file, passes it through and deletes it

Upvotes: 2

Related Questions