How to download pdf files using jquery generated in php

0

I am trying to make file downloads dynamically, for this I use jquery. I am generating the pdf files from php with the Html2Pdf plugin (I have already solved that.) The issue is that:

I have "cards" with general user data. When clicking "download" the system has to validate: 1.- If you have permission to download 2 .- That the limit of downloads has not reached top.  If both conditions are validated, a pdf generated from php must be returned. Here's the problem, how do I send a pdf from php so I can download it from jquery? : /

I currently carry this:

Download action with jquery:

$('.descargarperfilbusqueda').click(function(){
        var token = $(this).attr('id');
        var datos = new FormData();
        datos.append("getpdfdescargar",true);
        datos.append("token",token);
        $.ajax({
            url:"../../views/ajax.php",
            method:"POST",
            dataType: 'JSON',
            data:datos,
            cache:false,
            contentType:false,
            processData:false,
            success: function(regreso){
                alert();
            }
        });
    });

File that receives the request ajax.php

if(isset($_POST['getpdfdescargar']) && $_POST['getpdfdescargar']==true){
        $instancia = privilegiosEmpresaController();
        $band = $instancia->permisoDescargar();

        if($band==true){
            //Aquí hago las instancias a los controladores correspondientes
//y genero ro el pdf. En resumen algo así.
require_once 'views/pdftemplates/cv.php';
        $html=ob_get_clean(); 
        $html2pdf = new HTML2PDF('P','A4','es','true','UTF-8', array(15, 10, 15, 10));
        $html2pdf->setDefaultFont('Arial');
        $html2pdf->writeHTML($html);

        ob_end_clean();

        $html2pdf->Output($path.$archivo, 'F');
        $salida =$path.$archivo;
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename="'.$archivo.'"');
        readfile($salida);
        }else{
            return flase;
        }

    }

The question is: In jquery (ajax) how do I receive that object to start downloading the file?

Edited : I published an answer that is not serving me at all, I explain: I am indicating to ajax that the object I am going to receive is a blob, and with the following code I start the download without problem.

$('.descargarperfilbusqueda').click(function(){
        var token = $(this).attr('id');
        var datos = new FormData();
        datos.append("getpdfdescargar",true);
        datos.append("token",token);
        $.ajax({
            url:"../../views/ajax.php",
            method:"POST",
            //dataType: 'JSON',
            data:datos,
            cache:false,
            contentType: false,
            processData:false,
            xhrFields: {
                responseType: 'blob'
            },
            success: function(regreso){

                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(regreso);
                    a.href = url;
                    a.download = 'archivo.pdf';
                    a.click();
                    window.URL.revokeObjectURL(url);
            }
        });
    });

Until then everything is fine, the problem is that before downloading the pdf I need to make several validations, for example: 1.- Validate the privilege for downloading. 2.- Validate that the limit has not reached the top, etc. Then the code I have it like this:

$('.descargarperfilbusqueda').click(function(){
        var token = $(this).attr('id');
        var datos = new FormData();
        datos.append("getpdfdescargar",true);
        datos.append("token",token);
        $.ajax({
            url:"../../views/ajax.php",
            method:"POST",
            //dataType: 'JSON',
            data:datos,
            cache:false,
            contentType: false,
            processData:false,
            xhrFields: {
                responseType: 'blob'
            },
            success: function(regreso){
                alert(regreso);
                console.log(regreso);
                if(regreso===0){
                    swal({
                        title: ':(',
                        text: 'No cuentas con privilegios para realizar esta acción.',
                        button: {
                          text: "OK",
                          value: true,
                          visible: true,
                          className: "btn btn-primary"
                        }
                      })
                }else if(regreso===1){
                    swal({
                        title: ':/',
                        text: 'Ocurrió un problema al intentar descargar el archivo. Por favor intenta nuevamente.',
                        button: {
                          text: "OK",
                          value: true,
                          visible: true,
                          className: "btn btn-primary"
                        }
                      })
                }
                else{
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(regreso);
                    a.href = url;
                    a.download = 'archivo.pdf';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            }
        });
    });

The problem? Ajax is receiving a blob object then my conditions to show the validation messages do not enter. I need to receive from the php server (true, false or the string of the pdf as the case may be) and already in jquery to convert it to blob only when it complies with the condition.

Note: This code helps me, that is, it generates and downloads the dpf correctly, but the warning messages (validations) do not work for obvious reasons.

How do I convert a string to a pdf blob file and start the download?

Thank you.

    
asked by Neftali Acosta 25.11.2018 в 11:51
source

2 answers

0

You could use the download attribute of the to html tag. For example:

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

This would have to "coordinate" with your php code so that once you generate the file, through ajax pass parameters so that jquery / js prepare the link or directly start downloading the file (as in the example above) .

Credit: Stackoverflow in English

Greetings!,

    
answered by 25.11.2018 в 16:42
0

At last I found the answer. To receive a pdf with ajax and start the download, the parameter is used:

xhrFields: {
         responseType: 'blob'
        },

In my case, after doing my validations my complete code was as follows:

$('.descargarperfilbusqueda').click(function(){
        var token = $(this).attr('id');
        var datos = new FormData();
        datos.append("getpdfdescargar",true);
        datos.append("token",token);
        $.ajax({
            url:"../../views/ajax.php",
            method:"POST",
            //dataType: 'JSON',
            data:datos,
            cache:false,
            contentType: false,
            processData:false,
            xhrFields: {
                responseType: 'blob'
            },
            success: function(regreso){
                alert(regreso);
                console.log(regreso);
                if(regreso===0){
                    swal({
                        title: ':(',
                        text: 'No cuentas con privilegios para realizar esta acción.',
                        button: {
                          text: "OK",
                          value: true,
                          visible: true,
                          className: "btn btn-primary"
                        }
                      })
                }else if(regreso===1){
                    swal({
                        title: ':/',
                        text: 'Ocurrió un problema al intentar descargar el archivo. Por favor intenta nuevamente.',
                        button: {
                          text: "OK",
                          value: true,
                          visible: true,
                          className: "btn btn-primary"
                        }
                      })
                }
                else{
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(regreso);
                    a.href = url;
                    a.download = 'archivo.pdf';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            }
        });
    });
    
answered by 26.11.2018 в 20:14