How to force a download with ajax?


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:

        var relatorio = $('.relatorios').html();

            type: "POST",
            url: "acao.php?acao=exportPDF",
            data: 'relatorio='+relatorio,
            cache: false,
            beforeSend: function() {
            complete: function() {
            success: function (retorno) {

                    title: 'Sucesso',
                    text: 'O download irá iniciar em breve.',
                    class_name: 'success'
            error: function(data) {

And I have the following code in PHP:

// Inclui classe DOMPDF

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

        $dompdf = new DOMPDF();


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 Matheus Jordan 03.05.2014 в 15:29

3 answers


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 .

answered by 04.05.2014 / 01:24

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.

answered by 03.05.2014 в 17:00

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 = ${
        protocol: url.protocol, //http|https
        host:, //localhost|
        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");
    $.fileDownload(href, {
        successCallback: function(url) {
            // após a requisição ser completada com sucesso, fecha o modal
            setTimeout(function() {
            }, 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');
    answered by 06.05.2014 в 23:37