1

i want to download a file using ajax via post request using jQuery.

here is the PHP code i am using.

if (file_exists($file)) {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    readfile($file);
}

and this is the jQuery.

$('button.erp_ci_download').click(function(){
    var formData = $('form#erp_customerinvoice').serialize();
    $.ajax({
        type: 'POST',
        url:  "App/Ajax/Excel/Download.php",
        data: formData
    });
});

is it not possible to download it this way? i tried googling and some suggested it is the same way i am doing it. but in my console it shows some garbage values as response.

where am i going wrong?

thank you..

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
  • I don't think it's possible to download via AJAX. why not redirect the user to the download page and have him download the file normally? – Madara's Ghost Dec 02 '11 at 14:36
  • I don't think it's possible to do this in an AJAX request. Also, it's pretty pointless as the browser will recognise the headers of the request as not being able to be viewed in the browser and will popup the download dialog box anyway. – Rory McCrossan Dec 02 '11 at 14:37

1 Answers1

4

You could simply send a POST request to your App/Ajax/Excel/Download.php page with the form data you wish and forget about using jQuery's AJAX. If your response headers are correct, when you post your "erp_customerinvoice" form, the browser will, by default, show you a download file dialog and you will never navigate to the Download.php page because the response headers will prevent a redirect.

See some related questions for more explanation and alternatives:

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • 1
    @IbrahimAzharArmar: But do it *without* the AJAX request. Just have a form where the action is `App/Ajax/Excel/Download.php` and submit it via POST (i.e. your `erp_customerinvoice` form). – Cᴏʀʏ Dec 02 '11 at 14:39