Export php data to xls from a link

Asked

Viewed 1,328 times

2

I’m making a link, that when the user clicks on it should generate an xls file. The link has the data-attributes and must pass these attributes to the.php page and generate the xls. I tried to do with jquery and it’s not working, is there some other way?

<a href="#" id="xls" data-unidade="203" data-tema="1">
    Gerar XLS
</a>

The jquery

$(document).ready(function() {
    $('#xls').click(function(event) {
        event.preventDefault();

        $.ajax({
            type: 'POST',
            url : 'produto/exportXls',
            data: {
                'tema_id' : $(this).data('tema'),
                'unidade_id' : $(this).data('unidade')
            }
        });
    });
});

php that creates the table to generate the xls

$html = '<table><tr>';
$html .= '<td colspan="3">Planilha teste</tr>';
$html .= '</tr>';
$html .= '<tr><td><b>Coluna 1</b></td><td><b>Coluna 2</b></td><td><b>Coluna 3</b></td></tr>';
$html .= '<tr><td>L1C1</td><td>L1C2</td><td>L1C3</td></tr>';
$html .= '<tr><td>L2C1</td><td>L2C2</td><td>L2C3</td></tr>';
$html .= '<tr><td>L3C1</td><td>L3C2</td><td>L3C3</td></tr>';
$html .= '</table>';

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/x-msexcel");
header("Content-Disposition: attachment; filename=arquivo.xls" );
header("Content-Description: PHP Generated Data" );
// Envia o conteúdo do arquivo
echo $html;

Only it’s not happening...

  • The html is displayed on the screen this is the problem?

  • 1

    actually does not display on the screen, only in firebub->Network->preview. And when I run the direct url it generates the xls file.

  • What’s the mistake? What was supposed to happen?

  • 3

    "Only it’s not happening..." is very vague. First isolate the problem: Does the application work without AJAX? If it works, the problem is in Javascript. If it doesn’t work, it’s in PHP. Second, in your AJAX, where is the callback success? Without it you can’t do anything with the server response. Third: Do you really need AJAX for that? Why not pass the arguments via querystring in a link once the file will be downloaded?

  • @Guilhermeoderdenge was to download the file.

  • @Brunoaugusto great questions you raised... I will test here and warning. I was wondering that clicking on the link will redirect you to the link page. But I will take the test.

Show 1 more comment

2 answers

4

In a free translation of the words of John Culviner, creator of the plugin jQuery File Download:

Javascript, by design, does not have the ability to perform low-level tasks on its users' computer for security reasons. Initializing a download dialog is one such limitation.

So anyway, you will have to generate the file on your server and have a valid URI that points to it. With PHP you can do something simple like using file_put_contents()

Once this is done, a crude solution would be callback successfully manually redirect the browser to the URI of that resource:

$.ajax({
    url: 'path/to/server/action',
    data: {
        'tema_id': $(this).data('tema'),
        'unidade_id': $(this).data('unidade')
    },
    success: function (data) {
        window.location.href='arquivo.xls';
    }
});

But that’s not very appealing to modern web standards. With the above plugin, not only do you compose a specific solution, but you offer a more elegant way of handling errors.

When the server responds by requesting that the response be treated as a download, if successful, the browser does not change the page the user is on and displays the appropriate dialog box.

But when there is an error (file does not exist, for example), the browser is redirected to the default 404 page which may even be written in Korean which is frustrating for the user.

  • 1

    One way that I had now achieved was by using this idea here http://stackoverflow.com/a/23504028/2161286 that worked, but so what I did was to link in its simplest form, without any js doing any kind of manipulation that then also worked and that is the most correct way, so I imagine by know and even by your answer. Valew

  • 3

    Anyway the physical file is created on the server, including with file_put_contents() itself (it is slower, but it is more practical). This is a great example that AJAX is not the cure for cancer. There are things you just can’t do or even can’t do, but you have to take a huge turn when you can solve with basic HTML.

1

1) Change the PHP call to a traditional, non-ajax link;

2) add the next header to force the download:

header("Content-type: application/force-download");  
  • Unless that header is needed by some stubborn browser, it is unnecessary because the Content-disposition would already deal with the download force definition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.