Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

Downloading Via JQuery AJAX Post not working

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

Upvotes: 1

Views: 8534

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107528

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:

Upvotes: 4

Related Questions