javascript - PHP Download via AJAX

530

I have a PHP script that allows a user to download a file. It works fine if I create a standard button on my form and, on post back, call the PHP script. However, I'm trying to have the button call some Javascript that then uses AJAX to call the PHP script. I don't get any errors but the file doesn't download.

//JAVASCRIPT
<script type="text/javascript">
function downloadForm()
{
    var data = {ipAddress : "<?php echo $ipAddress; ?>", userID : "<?php echo $userID; ?>"};
    jQuery.ajax({
        url: "/download-form-internal.php",
        type:'POST',
        data: data,
        dataType: 'html',
        success: function(result){

        },          
    });
}
</script>   

//PHP CODE SNIPPET
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename='.$FILENAME);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
flush();
echo $fileToDownload;
exit();

Thanks for any help!

837

Answer

Solution:

You havesuccess: function may be you need to adderror: function to see errors.

And also why you send echo and before send header! Header is need to send first.

People are also looking for solutions to the problem: php - Where to use session_write_close(), in ajax

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.