Download File Through an Ajax Call PHP

Download file through an ajax call php

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

download file using an ajax request

Update April 27, 2015

Up and coming to the HTML5 scene is the download attribute. It's supported in Firefox and Chrome, and soon to come to IE11. Depending on your needs, you could use it instead of an AJAX request (or using window.location) so long as the file you want to download is on the same origin as your site.

You could always make the AJAX request/window.location a fallback by using some JavaScript to test if download is supported and if not, switching it to call window.location.

Original answer

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.

$.ajax({
url: 'download.php',
type: 'POST',
success: function() {
window.location = 'download.php';
}
});

Even though this answers the question, it's better to just use window.location and avoid the AJAX request entirely.

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!'));

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?

Download not working in php through ajax call

I resoved it by following code

  function download(document_unique_name,document_actual_name) 
{
window.location = '../common/downloadFile.php?document_unique_name='+document_unique_name+'&document_actual_name='+document_actual_name;
}

It worked for me !!!

Force Download via Ajax and PHP

You can't download files with ajax. So, if you have something that should happen on ajax, you should return url in response and apply it like document.location = "url"to start download process.

One note here. As I remember, browser will block file download if it is initiated not by user click. So, this will work fine:

.click(function(){
document.location = "download url"
})

But if it is started not by user click, it will be blocked. So, code like this:

.click(function(){
$.ajax({...,
success:function(download_url_from_server){
document.location = download_url_from_server;
}});
})

will be blocked by browser. So, if you want to pass some data with a post, you may submit a form into hidden iframe or to blank page using <form target="...":

 function checkToken(token){
var $form = $("#downloadForm");
if ($form.length == 0) {
$form = $("<form>").attr({ "target": "_blank", "id": "downloadForm", "method": "POST", "action": "script.php" }).hide();
$("body").append($form);
}
$form.find("input").remove();
var args = { a: "checkToken", b: token }
for (var field in args) {
$form.append($("<input>").attr({"value":args[field], "name":field}));
}
$form.submit();
}

And in script.php you need to execute code from download.php immediately, if token is Ok, or do a redirect to download script:

header("Location: download.php?a=" . $filename)

Dowload file with ajax and php

I'm not sure [my other solution with jQuery does not work in Firefox..]. Like many others said, you should not use AJAX/jQuery to make web browser download file.

Example:

page.htm with download link/button/anything:

<!doctype html>
<html>
<head>
<title>Download fake file from JS script example</title>
<meta charset="utf-8">
<script>
function downloadPdfExample()
{
// simple :)
window.location = "download_pdf.php";
}
</script>
</head>
<body>
Click on button below to start download:<br />
<button onclick="downloadPdfExample()">Start PDF download</button><br />

</body>
</html>

download_pdf.php file that will force browser to download file, not show in new card/current card:

<?php
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . urlencode(basename("form1.pdf")));
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
readfile("example.pdf");

flush();

I thought too much about JS code and forgot about PHP.

As you can see in example on PHP page ( http://php.net/manual/en/function.readfile.php#example-2524 ) readfile('filename'); does not return file content. It prints it on 'output'!

So.. this part of code:

$response = readfile("form1.pdf");
header('Content-Length:' . strlen($response));

Throws error! You cannot set response header AFTER you send file content (readfile send file content to browser, not put it variable $response!)

In $response is LENGTH of data sent to browser, so strlen($reponse) also does not work.

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);
}
}


Related Topics



Leave a reply



Submit