How to force a download with ajax?

6

I'm using the PHP DOMPDF class to generate accounts with dynamic filters.

The user selects the filters in a form and asks to generate, so far so good. But it will have the option of exporting what it has filtered into PDF.

Today, I have the following jQuery code:

$('#exportPDF').click(function(){
        var relatorio = $('.relatorios').html();

        $.ajax({
            type: "POST",
            url: "acao.php?acao=exportPDF",
            data: 'relatorio='+relatorio,
            cache: false,
            beforeSend: function() {
                $('#loader').fadeIn(500);
            },
            complete: function() {
                $('#loader').fadeOut(500);
            },
            success: function (retorno) {
                console.log(retorno);
                $('.relatorios').html(retorno);

                // RETORNA MENSAGEM DE SUCESSO
                $.gritter.add({
                    title: 'Sucesso',
                    text: 'O download irá iniciar em breve.',
                    class_name: 'success'
                 });
            },
            error: function(data) {
                console.log(data);
            }
        });
    });

And I have the following code in PHP:

// Inclui classe DOMPDF
        require_once("../../../include/class/dompdf/dompdf_config.inc.php");

        // Recebe a tabela
        $relatorio = $_POST['relatorio'];

        $dompdf = new DOMPDF();

        $dompdf->load_html($relatorio);
        $dompdf->render();
        $dompdf->stream('relatorio_cliente.pdf');

The idea would be that when generating the PDF by PHP Ajax would send the download request to the browser / client and the entire process flow. I've tried using the headers in PHP and Ajax itself, among many other things. I have also searched for this on the internet and I have already encountered some problems that are just like mine, I just did not understand it very well.

Can you do this?

    
asked by anonymous 03.05.2014 / 15:29

3 answers

6

If I'm not mistaken, what you're doing works for some browsers, but not for others. An alternative is to continue doing the ajax request, and save the PDF to disk instead of trying to serve it as a return of that request. Instead, pass the URL of the saved file as a response, and in% ajax% function use success .

    
04.05.2014 / 01:24
1

I have already done this and I have not succeeded either. AJAX does not receive PDFs. In that case, I did not use ajax. I just opened on a new page (_blank) forcing the download and after the download was done the page was closed automatically.

    
03.05.2014 / 17:00
1

I went through a similar problem. After searching a bit (a lot) on the net, I found this plugin: jQuery File Download (I recommend using along with this: jQuery URL Decoder )

The use is very simple, but there is a little trick that gave me a lot of headache until I found:

  • Refer to the plugin jquery.urldecoder.min.js
  • Refer to the plugin jquery.fileDownload.js
  • Sample my code:

    var url = $.url.parse(window.location.href);
    
    var href = $.url.build({
        protocol: url.protocol, //http|https
        host: url.host, //localhost|contoso.com
        port: url.port, //porta do web server 
        path: url.path + 'pdf.php', // url que receberá a requisição
        params: {
            param1: 'val1',
            param2: 'val2',
            param3: 'val3',
            paramN: 'valN',
        }
    });
    // output:
    // http:// localhost:80/pdf.php?param1=param1&param2=param2&param3=param3
    
    // prepara um modal de aviso ao usuário informando que o arquivo está sendo gerado (bootstrap)
    var preparingFileModal = $("#preparing-file");
    preparingFileModal.modal();
    
    $.fileDownload(href, {
        successCallback: function(url) {
            // após a requisição ser completada com sucesso, fecha o modal
            setTimeout(function() {
                preparingFileModal.modal('hide');
            }, 3000);
        },
        failCallback: function(url) {
            // caso haja um erro na requisição, altera a mensagem do modal para callback do usuário
            preparingFileModal.find('.modal-body p').first().html('Ocorreu um erro ao tentar baixar o PDF.\n\nTente novamente mais tarde');
        }
    });
    
        
    06.05.2014 / 23:37