File download script doesn't work when called from Ajax
You cannot use AJAX to download files. It doesn't make sense. You can send the AJAX request and fetch the file contents inside the success handler on the client, but for obvious security reasons you can't do much with it. You cannot save it on the client computer and there's no javascript API allowing you to prompt the user where to save it.
So to download files, don't use AJAX. Create an anchor pointing to your server side script that serves the file to be downloaded.
PHP download script does not work when called via AJAX
you missunderstand what XMLHttpRequest is for
, it's used mainly for reactivity , for example when we want to load a list generated by php without having to reload the page ,
you can achive it with it , but since you don't need it
a simple way would be to open a _blank window to the link you gave so your function will look like
function downloadGPXfile(fn) {
let script = `downloadGPXfile.php?filename=${fn}`;
window.open('http://website/downloadGPXfile.php?filename=' + fn, '_blank');
}
and after the download dialog get showen the window is closed so your php will look like
<?php
$dir = 'download/';
$file = $_GET['filename'];
$fqn = $dir . $file;
$fileSize = filesize($fqn);
header("Content-Type: text/xml");
header("Content-Disposition: attachment; filename=\"$file\"");
header("Content-Length: $fileSize");
readfile($fqn);
echo "
<script>
window.close();
</script>";
?>
if this doesn't work for you although just to be clear the window will be shown for like 1sec maximum and then closed you can use
function downloadGPXfile(fn) {
let fileurl = `http://website/downloadGPXfile.php?filename=${fn}`;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var downloadUrl = URL.createObjectURL(xhttp.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = downloadUrl;
a.download = "";
a.click();
}
};
xhttp.open("GET", fileurl, true);
xhttp.responseType = "blob";
xhttp.send();
}
you see you need to stimulate like the user clicked an that has the object
File downloading using AJAX not working
You are using $("#display").after(html);
thats why its displaying the content of the file. You can download the file by following code.
$(function() {
$(".download_link").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
$.ajax({
type: "POST",
url: "download_file.php",
data: dataString,
cache: false,
success: function(html){
window.location = 'your_file.pdf';
}
});
return true;
});
});
Download a file by jQuery.Ajax
2019 modern browsers update
This is the approach I'd now recommend with a few caveats:
- A relatively modern browser is required
- If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // the filename you want a.download = 'todo-1.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('your file has downloaded!'); // or you know, something with better UX... }) .catch(() => alert('oh no!'));
PHP file download: PHP is sending file data in ajax response but file is not downloading
Change the server function so it uses a get
parameter. Then open a new window with the script URL.
function download() {
var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
var url = "download?path=" + encodeURIComponent(path); //it is a code ignitor project hence it is just an action call.
window.open(url);
});
public function download() {
$path = $this->input->get('path');
if(!file_exists($path)){
die('file not found');
} else {
header("Content-Disposition: attachment; filename=" . basename($path) . "");
header("Content-Length: " . filesize($path));
header("Content-Type: application/octet-stream;");
readfile($path);
}
}
Download file with ajax and php - readfile not working
You need to separate the functionality, that is, post the data to PHP first, save the content of the text file and then, in a second request, let the user download the file. So one (skeleton) approach would be:
JS File:
function exportColors() {
var exportData = this.dataset.id;
$.ajax({
type: "POST",
data: {data: exportData},
success: function (data) {
// redirect or print out a link
}
});
}
PHP File for the first request (saving the content):
<?php
if (isset($_POST['data'])) {
$handle = fopen("file.txt", "w");
fwrite($handle, $_POST['data']);
fclose($handle);
// give back some unique id or the unique filepath
}
?>
PHP File for the second request (be it through clicking on a link or after having been redirected):
// essentially everything that outputs your file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
Comments:
Either give back a unique filepath or via a handle through a database (more secure, but more complex as well). Besides, why should the user download the unchanged data he has formerly submitted? Is there more to it than meets the eye?
Handle file download from ajax post
Create a form, use the POST method, submit the form - there's no need for an iframe. When the server page responds to the request, write a response header for the mime type of the file, and it will present a download dialog - I've done this a number of times.
You want content-type of application/download - just search for how to provide a download for whatever language you're using.
Related Topics
Convert PHP Array String into an Array
Distance Calculations in MySQL Queries
Getting the Text Portion of a Node Using PHP Simple Xml
Illegal Command Error Code 127 in PHP Exec Function
How to Remove <Br /> Tags and More from a String
Laravel: I Can't Send More Then 2 Variables from Controller to a View
JSON VS. Serialized Array in Database
Laravel Check If Collection Is Empty
Browscap Ini Directive Not Set
How to Use PHP to Connect to SQL Server
Utf-8 Not Working in HTML Forms
PHP Remember File Field Contents
Override External Product Url to "Add to Cart" Product Button
How to Remove the Fatal Error When Fetching an Assoc Array