0

I'm trying to export some tables generated with PHP from MySQL data. I'm trying to send the info via AJAX to a file with this code:

<?php
header("Content-type: application/vnd.ms-excel; name='excel'");  
header("Content-Disposition: filename=excel.xls");  
header("Pragma: no-cache");  
header("Expires: 0");  
echo $_POST['table'];
?>

The data comes from this function

function export_excel (id_table) {
    var table =  $("#" + id_table).html();
    $.ajax({
            type: 'POST',
            url: 'toexcel.php',
            data: 'table='+table
        });
}

Through Firebug I can see that the table is echoed correctly but it doesn't start any download. Which could be the problem?

1 Answer 1

2

It is not possible to start a file download as a response to an Ajax request. You have to send the browser to fetch the resource like if you were navigating to a page.

If you need to use the POST method, I think the ideal way to do this would be:

  • Have a real <form> element into which you write the POST data

  • Have an invisible or small iframe. Give it a name

  • Give the form the iframe name as the target property

  • submit() the form

if all headers are set correctly (You may have to add some more, like Content-disposition: attachment), this should trigger a file download without affecting your current page.

If you can use GET, a simple

location.href="toexcel.php?param1=value1&param2=value2"

should do already.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.