Ajax File Download Using Jquery, PHP

Ajax File Download using Jquery, PHP

I think the problem is that you're trying to load a file result INTO #downloadmsg, which isn't going to work because .load() is only going to load results as HTML...NOT binary data or other encoding.

One approach that might work is creating a hidden iframe in HTML, like this:

<iframe id="secretIFrame" src="" style="display:none; visibility:hidden;"></iframe>

Then, set the attr of the iframe to your querystring:

$("#secretIFrame").attr("src","myphpscript.php?option1=apple&option2=orange");

and then using PHP headers to force the download when the source is set (here's an example of an exporter header set from one of my scripts that uses an octet stream):

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=data.xls ");
header("Content-Transfer-Encoding: binary ");

Hope this helps!

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

Downloading PDF file with JQuery AJAX and PHP

i don't think this approach to downloading a pdf will work. Javascript is sending the request, and php is sending the response. You want the response to go directly to the browser, not to javascript. You should change the download link to go directly to the download location. No ajax / javascript needed. Like this:

<a href="javascript:void(0)" onclick = "window.href='app/myPage/download?'+id">download</a>

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 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 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 = ....

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.

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

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