Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.6K
Vistas
TCPDF - AJAX - Download file without saving it to webserver from AJAX call

I have an AJAX call to the create_pdf.php page:

$('body').on('click', '.PrintButtonWithClass', function (event) {
    var1 = $('#id1').val();
    var2 = $('#id2').val();
    dataString='var1='+var1+'&var2='+var2+'&pdf_name=PdfName&pdf_creator=myname';

    $.ajax({ 
        type: 'post',
        url: '/path/to/createpdf/file/create_pdf.php',
        data: dataString,
        success: function (data) {
            alert('success');
        }
    });
});

In create_pdf.php I tried to use this line to download the file:

$pdf->Output(str_replace(' ','_',utf8_decode($_POST['pdf_name'])).'.pdf', 'D');

I tried also the FD and I parameters with no success, the file does not get downloaded.

How can I force downloading the file created without saving it to the webserver and without redirecting user to any other page? I want him to stay on the same page, and that the browser pops up a (download or preview dialog box) for the PDF. Is there any way to do it?

EDIT : create_pdf.php is Waiting for POST variables. and uses them to create the HMTL for the pdf.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can try to submit the form to a new window( like a popup ):

<form method="post" id="myform" action="your_url">
    <input name="param1">
</form>

And in javascript

// create popup window
var wind = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');

// submit form to popup window
$("#myform").attr("target", "__foo");

Do not forget to send content-type header from php:

header("Content-Type", "application/pdf");

Edit: Browsers should display your pdf content and also show download or print options. The code is not tested but I think it would do what you requested;

over 4 years ago · Santiago Trujillo Denunciar

0

I found a work-around for my problem.

I did an AJAX call inside another AJAX call.

the first AJAX call creates the file on webServer and opens the file in a new Window.

In his success parameter I do the following:

The second AJAX call that deletes the file from Server.

            $.ajax({ 
                type: 'post',
                url: '/path/to/create_pdf.php',
                data: dataString,
                success: function (data) {

                window.open(
                  data,
                  '_blank' // <- This is what makes it open in a new window.
                );


                window.setTimeout(function () {
                    dataString2 = 'Downloaded=true';
                            $.ajax({
                                type: 'post',
                                url: '/path/to/create_pdf.php',
                                data: dataString2,
                                success: function (data) { alert(data); }, // handler if second request succeeds 
                            });
                }, 5000);



                    },

                  });
over 4 years ago · Santiago Trujillo Denunciar

0

Using this answer to my similar request : send a csv file from php to browser

I needed to (1) get and display a pdf in another window; and (2) get a CSV file and prompt for saving.

I have 2 simple buttons on the page (http://potoococha.net/) for each. Here is the code:

function getCSVText(evt)  {

  if (currentChecklistCountry)  {

    var form = $('<form method="post" action="../php/sendCSV.php?country=' + currentChecklistCountry + '"></form>');

    $('body').append(form);

    form.submit();

    form.remove();
  }
  else  checklistCountryButton.classList.add("needsAttention");
}

function openChecklistPage()  {

   if (!currentChecklistCountry)  {
       checklistCountryButton.innerHTML = "Select Country";
       checklistCountryButton.classList.add("needsAttention");
       return;
    }

   if (gNumDays == undefined) gNumDays = 12;

   vars = "?country="     + currentChecklistCountry;
   vars += "&num_days="   + gNumDays;
   vars += "&line_nos="   + lineNumbers.checked;
   vars += "&left_check=" + leftCheck.checked;
   vars += "&endemics="   + showEndemics.checked;
   vars += "&sci_names="  + !sciNames.checked;
   vars += "&italics="    + !italics.checked;

   window.open( '../php/makePDF.php' + vars, '_blank' );
}

So the getCSVText() methods downloads a file using a temporary form appended and then immediately removed, and openChecklistPage() successfully opens another browser window with a pdf file. The pdf file is never saved on the server. The CSV file is already stored there and just retrieved. Perhaps you can modify the code for your purposes.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda