I am creating a zip file download system in php with jquery ajax.
When the user clicks the download button, the request goes to the server and returns the filename.
I am able to download the file but it shows the name of the entire file along with the file path in console. I do not want this.
<button onclick="checkPayment(this.id)" id="filetoDownload_1">Download File</button>
Javascript
function checkPayment(data){
$.ajax({
type: 'post',
url: '../download.php',
data: data,
async: false,
success: function(result) {
let returnkd = JSON.parse(result);
if(returnkd["status"]){
$("#success").html(`<div class="card"><div class="card-body bg-white text-black">Download will start soon...</div></div>`);
setTimeout(() => {
window.location.href = returnkd["filename"];
}, 2000);
}else{
$("#error").html(`<div class="card"><div class="card-body bg-white">Something wents wrong... contact admin</div></div>`);
}
}
});
}
PHP
// wothout header
if(isset($_POST)){
some code
return array("status"=>true,"filename"=>"../folder/filename.zip");
}
// with header
if(isset($_POST)){
some code here
downloadFile($filename);
return array("status"=>true,"filename"=>"../folder/filename.zip");
}
function downloadFile($filename)
{
$filename = $filename;
$filepath = "../".$filename;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . $filename . '"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($filepath));
ob_end_flush();
#readfile($filepath);
}
how to download file without redirecting window.location.href or showing filepath in console.
i have tried php header but it doesn't work
I am trying to get my php script to download an image which the name of is being sent in from an ajax function in my javascript, and I think I'm using all the right headers and then I'm using readfile() to download the image, and when I preview the php when it runs with the chrome developer tools (ctrl+shift+i-> network -> XHR -> preview) all I get is a bunch of gibberish binary and my image doesn't download. Does anyone know why this is happening/how to fix it?
Here's my ajax which is just in a function that runs when a "download" button is clicked
$.ajax({
type: "POST",
url: 'requestAJAX.php',
data: {request: request, download: imageName},
success: function(){
console.log("Request Completed: " + request);
} // success
});
and here's my "requestAJAX.php"
<?php
switch ($_POST["request"]) {
case "download":
// Get parameters
$file = $_POST["download"];
$filepath = "UploadedImages/" . $file;
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file.'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
ob_clean();
flush();
// download
readfile($filepath);
exit;
} // if
break;
default:
echo "No request was made";
}
?>
and this is what I'm getting when I preview (not sure how it will help)
ÿØÿàJFIFHHÿâ#ICC_PROFILE0appl mntrRGB XYZ ÙacspAPPLapplöÖÓ-appldscmòdescüogXYZlwtptrXYZbXYZ¨rTRC¼cprtÌ8chad,gTRC¼bTRC¼mlucenUS&~esES&daDK.êdeDE,¨fiFI(ÜfrFU(*itIT(VnlNL(nbNO&ptBR&svSE&jaJPRkoKR#zhTWlzhCNÔruRU"¤plPL,ÆYleinen RGB-profiiliGenerisk RGB-profilProfil Générique RVBN, RGB 0×0í0Õ0¡0¤0ëu( RGB r_icÏðPerfil RGB GenéricoAllgemeines RGB-Profilfn RGB cÏðeNöGenerel RGB-beskrivelseAlgemeen RGB-profielÇ|¼ RGB Õ¸\ÓÇ|Profilo RGB GenericoGeneric RGB Profile1I89 ?#>D8;L RGBUniwersalny profil RGBdescGeneric RGB ProfileGeneric RGB ProfileXYZ Zu¬s4XYZ óRÏXYZ tM=îÐXYZ (¸6curvÍtextCopyright 2007 Apple Inc., all rights reserved.sf32BÞÿÿó&ýÿÿû¢ÿÿý£ÜÀlÿáExifMM*JR(iZHH é ¡ÿÛC
Thanks in advance for any assistance!
I am trying to download a pdf when clicking on a link.
I called function onlick of a link and in Codeigniter i wrote a function to download PDF file but when running URL ,file is downloaded but when triggered using click of link, its not working.
Controller:
function downloadpdf($pid)
{ set_time_limit(0);
$url="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf";
$file = basename($url);
$fp = fopen($file, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
echo "success";
}
My code ajax:
function DownLoadPdf(id)
{
url = "<?php echo base_url();?>admin/packages/downloadpdf/"+id;
$.ajax({
type:'POST',
url: url,
data : { pid : id},
success : function(response) {
console.log(response);
},
error : function(response) {
console.log("error");
}
});
}
View:
echo ' Download Attachment';
As far as ajax is concerned you cannot do that via ajax because ajax is not made for this purpose,its an asynchronous call that will give you a result. But you can do this without using any jquery, ajax at all
<a href="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf" download> Download Attachment</a>
Where $pid is the id you want to download the file. The download attribute will force the file to download. Cheers
I have one PHP file and other JavaScript. In JavaScript, I pass the variable with location of place where the file exists but on the PHP side doesn't recognize and doesn't properly download the file.
Code of JavaScript:
var nameFile = oEvent.getParameters().listItem.getTitle();
var directory = "C:/xampp/htdocsui5launchpad/WebContent/documents/";
window.location =directory;
$.ajax({
url: 'http://localhost/ui5launchpad/WebContent/php/downloadPDF.php',
type: 'POST',
datatype: "json",
data: { album: nameFile },
success: function (response, data, xhr) {
window.location = 'http://localhost/ui5launchpad/WebContent/php/downloadPDF.php';
},
error: function (response) {
console.log("Error in PHP, downloadPDF.php ");
}
});
PHP code:
if(isset($_POST["album"])){
$name = $_POST["album"];
}
$dir = "C:/xampp/htdocs/ui5launchpad/WebContent/documents/";
$file = $dir . $name;
if( isset($file)) {
//echo $file;
if (file_exists($file)) {
//echo $file;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
Can you help me, please ?
Thanks
You don't need to use ajax to download a file. Just link the file direct to the browser.
In the link tag put the attribute like this:
<a href="http://example.com/file.pdf" download>Download</a>
I managed to get my previous project working where I click a button on a webpage and it makes some text change on the webpage for all the devices that are viewing it, by making the button click run PHP code which tells all devices to run a JavaScript function, which reads the value of a text file that the PHP code is changing.
Now I want to do the same thing, but I want to have 3 different buttons that are running 3 different JavaScript functions on all the devices viewing the webpage.
I have tried making 3 different PHP files, and 3 different text files, and 3 different functions, but it didn't work (it seemed to think I was clicking the buttons when I wasn't), and also seemed like not a very efficient way to do it. I think it was to do with having multiple $.get() functions running at once, for all the different functions.
How would I have 1 PHP file, and 1 $.get() function and make this work?
Thanks,
Fjpackard.
Edit:
Here is the code I tried, although I would like it if I could do it a different and more efficient way if possible.
index.html:
<title>PHP Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var theButton;
function myClick()
{
$.post('script.php', {});
}
function myClick2()
{
$.post('script2.php', {});
}
function myClick3()
{
$.post('script3.php', {});
}
function myFunc() {
//The code you want to run on the clients
$("#theDiv").text("Say Hello");
setTimeout(function(){
$("#theDiv").text("");
},2000);
}
function myFunc2() {
//The code you want to run on the clients
$("#theDiv").text("Say Goodbye");
setTimeout(function(){
$("#theDiv").text("");
},2000);
}
function myFunc3() {
//The code you want to run on the clients
$("#theDiv").text("Zip Your Mouth");
setTimeout(function(){
$("#theDiv").text("");
},2000);
}
var lastValue = '';
var lastValue2 = '';
var lastValue3 = '';
$("document").ready(function() {
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
// mobile code here
$("#btn1").remove();
$("#btn2").remove();
$("#btn3").remove();
setInterval(function() {
$.get(
'script.php',
{},
function (data) {
if (data != lastValue) {
myFunc();
lastValue = data;
}
}
);
/*$.get(
'script2.php',
{},
function (data2) {
if (data2 != lastValue2) {
myFunc2();
lastValue = data2;
}
}
);
$.get(
'script3.php',
{},
function (data3) {
if (data3 != lastValue3) {
myFunc3();
lastValue = data3;
}
}
);*/
},100);
}
else {
$("#theDiv").remove();
}
});
</script>
<div id="theDiv"></div>
<button id="btn1" class="btn" onclick="myClick()">Say Hello</button><br>
<button id="btn2" class="btn" onclick="myClick2()">Say Goodbye</button><br>
<button id="btn3" class="btn" onclick="myClick3()">Zip Your Mouth</button>
script.php:
<?php
// Disable cache
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header("Pragma: no-cache");
$file = 'file.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// POST request
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
}
else
{
// not POST request, we assume it's GET
echo file_get_contents($file);
}
exit();
?>
script2.php:
<?php
// Disable cache
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header("Pragma: no-cache");
$file = 'file2.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// POST request
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
}
else
{
// not POST request, we assume it's GET
echo file_get_contents($file);
}
exit();
?>
script3.php:
<?php
// Disable cache
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header("Pragma: no-cache");
$file = 'file3.txt';
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// POST request
$previous = file_get_contents($file);
if ($previous === 'true')
{
file_put_contents($file, 'false');
}
else
{
file_put_contents($file, 'true');
}
}
else
{
// not POST request, we assume it's GET
echo file_get_contents($file);
}
exit();
?>
You could use some GET parameters and an array in the php file:
JS code:
function myClick()
{
$.post('script.php?button=1', {});
}
function myClick2()
{
$.post('script.php?button=2', {});
}
function myClick3()
{
$.post('script.php?button=3', {});
}
And then in script.php:
<?php
session_start();
// Disable cache
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header("Pragma: no-cache");
$fileArray = array("1" => "file.txt", "2" => 'file2.txt', "3" => 'file3.txt');
if(isset($_SESSION['lastFile']) && !isset($_GET['button'])){
$file = $_SESSION['lastFile'];
}else if(isset($_GET['button'])){
$file = $fileArray[$_GET['button']];
}else{
$file = "file.txt";
}
$_SESSION['lastFile'] = $file;
This way, if no GET parameter is set, the script will fall back on an previous used file ( set in the session ), or else load the default ( file.txt )
So if you do the Ajax request to script.php?button=2, file file2.txt will be loaded, and inserted into the session variable.
Later when you request script.php ( without the button part ), the script detects that there isn't any button get variable. But it knows there is an variable in the session with the previous used file, so the script will then load the previous used file.