4

I want to download a pdf file via a jquery post. I tried this:

$('#downloadPdf').click(function() {
    var id = $('#fileId').val();

    $.ajax({
        type: "POST",
        url: "includes/download_pdf.php",
        data: 'file_id=' + id,
        complete: function(data) {
            $('#pdf_results').html(data.responseText);
        }
    });
});

Code PHP:

<?php 
    $file_name = $_POST['file_id']; 
    // We'll be outputting a PDF header('Content-type: application/pdf'); 
    // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="'.$file_name.'.pdf"'); 
    // The PDF source is in original.pdf readfile('/var/www/vhosts/domain.nl/private/'.$file_name.'.pdf'); 
?>

When I use this code I get all strange signs in #pdf_results. I want to save the PDF to my computer but this doesnt work.

Somebody knows how to fix this?

Thanks in advance!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Leon van der Veen
  • 1,652
  • 11
  • 42
  • 60

4 Answers4

1

You don't need to use AJAX for this. Try to use something like this:

$(function(){
    $('#downloadPdf').click(function(){
        var id = $('#fileId').val();
        window.open(location.protocol + '//' + location.hostname + '/includes/download_pdf.php?file_id=' + id);
        return false;
    });
});

Cheers!

Igor Timoshenko
  • 1,001
  • 3
  • 14
  • 27
1

There is no need for ajax here.

Try using Rory McCrossan's solution: POST to server, receive PDF, deliver to user w/ jQuery

Either use the plugin or simply link to the file and make sure your server sends the correct headers (else you can read the file with php and output it from there: http://www.saschakimmel.com/2009/05/php-prompt-the-user-to-download-a-specific-file/)

Community
  • 1
  • 1
Fender
  • 3,055
  • 1
  • 17
  • 25
1

Have an invisible <iframe/> on the page, and create a <form> with attributes method="POST" action="includes/download_pdf.php" target="name_of_the_iframe", add a <input type="hidden" name="file_id" value="the_value"/> into it, and submit it.

All of the above can be done all in JavaScript without the need to put that kind of markup into the page, to keep things clean. And none of this is ajax.

Etienne Perot
  • 4,764
  • 7
  • 40
  • 50
1

You need to achieve this : I didn't really trace your program but you need the content disposition line in your php to make it work.

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
**header('Content-Disposition: attachment; filename="downloaded.pdf"');**

// The PDF source is in original.pdf
readfile('original.pdf');
?>

check the manual here

Also you can move the file over onto an iframe but that's a security risk, hence another topic.

hayonj
  • 1,429
  • 3
  • 21
  • 28
  • Good answer, the key is `attachment`, and to download it with javascript: `window.location = "includes/download_pdf.php"`; – jscripter Feb 07 '15 at 20:31