0

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 '<a  href="javascript:void()" title="Hapus" onclick="DownLoadPdf(' . "'" . $cdata[0]->package_id . "'" . ')"> Download Attachment</a>';
Amit Gupta
  • 2,771
  • 2
  • 17
  • 31
user7441072
  • 285
  • 1
  • 4
  • 17
  • I guess you have a problem in creating URL for the file here $url="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf"; $file = basename($url); can you please tell me the output of $file here. – M K Garwa Jan 03 '18 at 10:17
  • check this article. It might help you. https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – M K Garwa Jan 03 '18 at 10:20

1 Answers1

0

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