I'm trying to return the results of a db_query as a raw text file. The php solution uses header() to instruct browsers to download content. I've attempted using header() in an AJAX callback function, but the following error code is always returned:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText: this is just a test
I'm looking for a way to save a php string value to a file client-side, ideally without requiring the file to first be saved on the server. Alternatively, if I could pass a value from an AJAX callback directly to javascript for post-processing, that would work too (haven't found an AJAX callback with this capability).
Here's my test code (that produces the above error):
<?php
function test_download_form($form, &$form_state) {
$form['form_wrapper'] = array(
'#prefix' => '<div id="form_wrapper">',
'#suffix' => '</div>',
);
$form['form_wrapper']['download_submit'] = array(
'#type' => 'button',
'#value' => 'test download',
'#id' => 'download_submit',
'#ajax' => array(
'callback' => 'test_download',
),
);
return $form;
}
function test_download($form, $form_state) {
$dateFile = rand(10000000, 99999999)."_test.txt";
$dataString = "this is just a test";
//header() and drupal_add_http_header() behave the same
header('Content-Type: application/text');
header('Content-Disposition: attachment; filename="'.$dateFile.'"');
/*
drupal_add_http_header('Content-Type', 'application/text; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename="'.$dateFile.'"');
drupal_send_headers();
*/
echo $dataString;
exit;
}
location.href = '/path/to/file'
, or add a route which takes the string as a parameter and delivers the text file from memory, and set that instead (e.g.location.href = '/download-string?string=Foo';
). You also might need to useapplication/octet-stream
as theContent-Type
header to get it workingconst blob = new Blob([plaintext], {type: 'application/octet-binary', endings: 'native'});link.attr('href', URL.createObjectURL(blob));const link = $('#your-link'); link.attr('href', URL.createObjectURL(blob));link.attr('download', 'file.txt');
As long as your file name contains the correct extension it does not matter type is binary. You can see this approach working here .