Lennart
Lennart

Reputation: 1028

Force download with javascript

I have a php file like this:

<?php

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"my-data.csv\"");

$data = stripcslashes($_REQUEST['data']);
echo $data; 

?>

I can post (proper formatted) data to it and it will return a csv file. I do that like this:

    var data = $('table').toCSV('tbody > tr');
    $('table').addEvent('click', function(){            
        new Request({
                url: 'getCSV.php',
                method: 'post'                  
        }).send('data=' + data);            
    }); 

In Firebug I can see the request works and the response is ok. But the Download dialog does not pop up; how to fix that? Do I need different headers in the PHP file?

Upvotes: 1

Views: 517

Answers (3)

Nils
Nils

Reputation: 2061

Another way to do this is to utilize an iframe. So when clicking the "download" button you inject the iframe in the page. After you can clean it up.

document.body.inject(
 new Element('iframe', {
    'src': 'http://url.to.download', 
    'style': {
        'display': 'none'
     }
 })
);

Upvotes: 0

Lennart
Lennart

Reputation: 1028

I changed the JS to this:

    var data = $('lijst').toCSV('tbody > tr');

    var form    = new Element('form', {method: 'post', action : 'getCSV.php'});
    var field   = new Element('input', {type: 'hidden', name: 'data', value: data});
    var submit  = new Element('input', {'type' : 'submit', 'value' : 'Download'});
    form.adopt(field,submit);

    form.inject($('lijst').getElement('caption'));

Which adds a nice download button to the table and as the browser follows a form submit, the download dialog pops up. Thanks for thinking with me.

Upvotes: 1

user899205
user899205

Reputation:

As Gavin said, ajax calls cannot force download, and response is simply saved into a variable. You must create a hidden form and POST data. Like this:

var data = $('table').toCSV('tbody > tr');

$('table').on('click', function(){            
    $('<form action="getCSV.php" target="_new" method="POST" style="display: none;">'+
        '<textarea name="data">'+data+'</textarea>'+
      '</form>')
    .appendTo('body')
    .submit();          
}); 

P.S I haven't tested it.

Upvotes: 1

Related Questions