Redirect to another page in button Accept and issue PDF document

4

I have this situation:

1.- Register my data and at the moment of clicking on Accept; records are saved and a PDF document is created with FPDF without any problem

<div class="row">
   <div class="text-center">
      <div class="col-md-3"></div>
      <div class="col-md-3">
         <button type="submit" class="btn btn-primary" onclick="this.disabled=true; this.value=’Enviando...’; this.form.submit()" id="btn-registrar">Aceptar</button>                       
      </div>
      <div class="col-md-3">
         <button type="button" class="btn btn-primary" id="btn-cancelar">Cancelar</button>
         <script type="text/javascript">
            document.getElementById("btn-cancelar").onclick = function () {
            location.href = "../menu.php";
            };
         </script>
      </div>
      <div class="col-md-3"></div>
   </div>
</div>
</form>

By clicking on accept, the file guarda.view.php which contains this code is sent by POST:

    <?php session_start();

if (isset($_SESSION['username'])) {

  require('verificar.view.php');


   echo'<script type="text/javascript">
    alert("DATOS ACTUALIZADOS GRACIAS");     
    window.location="../menu.php"
    </script>';

    } else {
  header('Location: ../index.php');
}

 ?>

2.- Within this code, we send the PDF with the information that was filled out in the form without any problem.

I need that: at the moment of saving the PDF I am redirected to the URL ../menu.php but the code does not do it. That is, it generates the PDF, it is saved in the computer but it is not redirected and it remains in the form where it was filling the data.

Here I leave a fragment of the beginning and end of the code to show the PDF.

<?php session_start();

if (isset($_SESSION['username'])) {

header("Content-Type: text/html; charset=utf-8");

$modelo=$_POST['modelo'];
$serie=$_POST['serie'];
$testigo1=$_POST['testigo1'];
$fecha_alta=$_SESSION['fecha_alta'];
$email_administrativo=$_SESSION['email_administrativo'];
$email_usuario=$_POST['email_usuario'];
$fecha1="Estando de acuerdo en lo antes señalado, firman como responsables en la ciudad de ".$_SESSION['ciudad']." el dia ".$_SESSION['fecha']."";

$config['db']=array(
         'host'=> 'localhost',
         'username'=>'root',
         'password'=>'*****',
         'dbname'=>'database'
         );

         $db=new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname'],$config['db']['username'],$config['db']['password']);
         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   

         try{/*AQUI VA TODO EL CUERPO DEL PDF/*

         catch(PDOException $e)
         {

         echo $sql . "<br>" . $e->getMessage();
         }      
         $db = null; 

} else {
  header('Location: ../index.php');
}
?>

Now then. Add the following This file saves the record.

    <?php session_start();
   if(isset($_POST["aceptar"]) && $_SERVER["REQUEST_METHOD"] == "POST"){

    if (isset($_SESSION['username'])) { 

         header("Content-Type: text/html; charset=utf-8");

$modelo=$_POST['modelo'];
$serie=$_POST['serie'];
$testigo1=$_POST['testigo1'];
$fecha_alta=$_SESSION['fecha_alta'];
$email_administrativo=$_SESSION['email_administrativo'];
$email_usuario=$_POST['email_usuario'];
$fecha1="Estando de acuerdo en lo antes señalado, firman como responsables en la ciudad de ".$_SESSION['ciudad']." el dia ".$_SESSION['fecha']."";

$config['db']=array(
         'host'=> 'localhost',
         'username'=>'root',
         'password'=>'*****',
         'dbname'=>'database'
         );

       $db=new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['dbname'],$config['db']['username'],$config['db']['password']);
         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   

         try{

         $sql="INSERT INTO 'custodia_equipo_electronico'(
       'fecha_alta',
       'numero_empleado',
       'nombre_completo',
       'empresa',
       'apoderado_legal',
       'modelo',
       'serie',
       'centro_laboral',      
       'gerente_administrativo',
       'testigo1',
       'fecha_expedicion',
       'email_administrativo',
       'email_usuario')
       VALUES
         (STR_TO_DATE('$fecha_alta', '%d/%m/%Y'),
       '{$_SESSION[numero]}',
       '{$_SESSION['nombre_completo']}',
       '{$_SESSION['empresa']}',
       '{$_SESSION['Apoderado_Legal']}',
       '$modelo',
       '$serie',
       '{$_SESSION['centro_laboral']}',
       '{$_SESSION['gerente_administrativo']}',
       '$testigo1',     
       '$fecha1',
       '$email_administrativo',
       '$email_usuario')";
       $db->exec("SET NAMES'utf8'");
       $db->exec($sql);
       $last_id = $db->lastInsertId(); 
       }   
       catch(PDOException $e)
         {      
         echo $sql . "<br>" . $e->getMessage();
         }     

       //$db = null; 
       //$sql = null; 
       //$sql1 = null; 
       //$conexion = null; 


         ?>
<html lang="es">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta http-equiv="X-UA-Compatible" content="IE=9" />
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Resultado</title>
      <link href="../libs/bootstrap/css/bootstrap.min.css" rel="stylesheet">
      <link rel="stylesheet" href="../libs/bootstrap/js/bootstrap.min.js">
      <link rel="stylesheet" href="../css/style.css" type="text/css" />
      <link rel="stylesheet" href="../css/form-elements.css" type="text/css" />
      <script src="../libs/js/Respond/src/respond.js"></script>
      <script src="../libs/js/Respond/src/matchmedia.addListener.js"></script>
      <script src="../libs/js/Respond/src/matchmedia.polyfill.js"></script>
   </head>
   <body>
      <div class="container">
         <div class="inner-bg">
            <div class="container">
               <div class="row">
                  <div class="col-sm-8 col-sm-offset-2 text">
                     <div class="text-center">
                        <img title="logo" src="../images/logogruver.png">                        
                     </div>
                  </div>
               </div>
               <div class="container">
                  <?php
                     echo "<script>alert('Custodia Registrada.');</script>"; 
                     echo "".$last_id."";
                        //require('verificar.view.php');
                        //header('Location: ../menu.php');
                     ?>
                  <br>
                  <br>
                  <div class="row">
                     <div class="text-center">
                        <div class="col-md-4">
                           <p>Regresar al Menú Principal:
                              <a href="../menu.php" class="btn btn-info btn-lg">
                              <span class="glyphicon glyphicon-home"></span> Menú 
                              </a>
                           </p>
                        </div>
                        <div class="col-md-4">
                           <p>Descargar PDF:
                              <a href="verificar.view.php" class="btn btn-info btn-lg" id="imprime">
                              <span class="glyphicon glyphicon-download-alt"></span> Descargar
                              </a>
                              <script>
                              $(function () {
                                 $('#imprime').on('click', function () {
                                    var last_id = $(this).data().last_id;
                                    $.post( 'verifica.view.php', { last_id: last_id } );
                                    });
                                });

                              </script>
                           </p>
                        </div>
                        <div class="col-md-4">
                           <p>Salir del Sistema:
                              <a href="../ldap/cerrar-sesion.php" class="btn btn-info btn-lg">
                              <span class="glyphicon glyphicon-off"></span> Salir 
                              </a>
                           </p>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
<?php
   } 
   else {   header('Location: ../index.php');   }
   }

   ?>

And on the button that says "Download PDF:" I need to generate the PDF and this is the code to generate the PDF

    <?php session_start();

if (isset($_SESSION['username'])) {      

         include('../conn/conexion_mb.php');

         $ultimo_registro=isset($_POST['last_id']);

         $sql1 = "SELECT * FROM custodia_equipo_electronico WHERE folio LIKE '$ultimo_re' ORDER BY folio ASC";
         mysqli_set_charset($conexion,"utf8");
         $resultado = $conexion->query($sql1);
         if ($resultado->num_rows > 0)
         {
             while($fila = $resultado->fetch_assoc())   {
             $folio=$fila['folio'];
             $fecha_alta=$fila['fecha_alta'];
             $numero_empleado=$fila['numero_empleado'];
             $nombre=$fila['nombre_completo'];
             $empresa=$fila['empresa'];
             $apoderado_legal=$fila['apoderado_legal'];
             $modelo=$fila['modelo'];
             $serie=$fila['serie'];
             $centro_laboral=$fila['centro_laboral'];
             $gerente_administrativo=$fila['gerente_administrativo'];
             $testigo1=$fila['testigo1'];
             $fecha_expedicion=$fila['fecha_expedicion'];   
             $email_administrativo=$fila['email_administrativo'];
             $email_usuario=$fila['email_usuario'];     }
         }
            else
         {
             echo'<script type="text/javascript">
             alert("NO EXISTEN DATOS EN LA BASE DE DATOS");
             window.location="../menu.php"
             </script>';
             exit;
         }

header("Content-Type: text/html; charset=utf-8");
include_once('../libs/fpdf/fpdf.php'); 
class PDF extends FPDF
{
    function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('Arial','I',8);
        $this->Cell(0,10,'Departamento de Sistemas','T',0,'C');
    }
    function Header()
    {

        $this->SetFont('Arial','B',16);
        $this->Cell(50);        
        $this->Cell(100,10,utf8_decode('Formato Custodia Equipo Electrónico'),0,0,'C');
        $this->Cell(30,10,'',0,0,'C',$this->Image('../images/logogruver.png', 169,6, 32));
        $this->Ln(15);
    }   
}

$pdf = new PDF();
$pdf->AddPage('P', 'Letter');
$pdf->SetFont('Arial','',9);
$pdf->Cell(0,1,'Folio : '.$folio.'',0,0,'L');
$pdf->Cell(50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("Por medio del presente instrumento, la empresa ".$_SESSION['empresa']." representada en este acto por C.P. ".$_SESSION['Apoderado_Legal']." en su carácter de apoderado legal, entrega el equipo  ".$modelo.", número de serie  ".$serie." al Sr.(a)  ".$_SESSION['nombre_completo']." actualmente laborando en la sucursal ".$_SESSION['centro_laboral'].".") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("El cual recibe a su entera satisfacción y en buenas condiciones de uso, obligándose a devolverlo en las mismas condiciones en que las que le fue asignado, considerando el deterioro normal y esperado del mismo, en el momento en que le sea requerido.") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("El equipo anteriormente descrito, es asignado como Herramienta de Trabajo en apoyo al desarrollo de sus actividades; su autorización se sustenta en la aprobación de la Dirección General de la empresa sujetándose a las siguientes condiciones:") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("1. El equipo se entrega al puesto, no a la persona, quedando en todo momento al servicio de la empresa.") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("2. El equipo estará asignado para el desarrollo del trabajo diario de su titular, debiendo pernoctar en la empresa en ausencias por vacaciones, permisos e incapacidades.
") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("3. El titular que ocupe el puesto, será el depositario, usuario y responsable único y total del bien recibido, quedando bajo su custodia la vigilancia y reporte oportuno de cualquier necesidad de mantenimiento.") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("4. En caso de robo, extravío o daños, que hagan imposible el uso óptimo del equipo y el titular responsable no pueda comprobar lo anterior o le sean imputables a él las causas, se cargarán a éste los daños y perjuicios causados a la empresa, aceptando y autorizando, desde este momento, se le realicen los descuentos en términos del artículo 110 de la Ley Federal de Trabajo.") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("5. Al momento en que el empleado se separe de la empresa, sea por la causa que fuere, se hará una valuación del estado actual del equipo, para que en caso de que por el mal uso del mismo éste se encontrara deteriorado, se le haga responsable de su demérito.
") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode("6. El equipo se entrega configurado y listo para el uso del personal, con entendido de que podrá ser solicitado en el momento que se requiera para una revisión física e interna del mismo, y en caso de encontrar alteraciones o uso inadecuado se procederá con un acta administrativa o el retiro del equipo
") ,0,'J',false);
$pdf->Cell (50,5,'',0,1);
$pdf->MultiCell(195,5,utf8_decode(''.$fecha1.'') ,0,'J',false);
$pdf->Cell(50,5,'',0,1);
$pdf->Cell(50,5,'',0,1);
$pdf->Cell(100,5,'___________________________________',0,0,'C');
$pdf->Cell(100,5,'___________________________________',0,1,'C');
$pdf->Cell(100,5,utf8_decode(''.$_SESSION['nombre_completo'].''),0,0,'C');
$pdf->Cell(100,5,utf8_decode(''.$_SESSION['Apoderado_Legal'].''),0,1,'C');
$pdf->Cell(100,5,'',0,0);
$pdf->Cell(100,5,'',0,1);
$pdf->Cell(100,5,'Usuario Final',0,0,'C');
$pdf->Cell(100,5,'Apoderado Legal',0,1,'C');
$pdf->Cell(100,5,'',0,0);
$pdf->Cell(100,5,'',0,1);
$pdf->Cell(100,5,'___________________________________',0,0,'C');
$pdf->Cell(100,5,'___________________________________',0,1,'C');
$pdf->Cell(100,5,utf8_decode(''.$_SESSION['gerente_administrativo'].''),0,0,'C');
$pdf->Cell(100,5,utf8_decode(''.$testigo1.''),0,1,'C');
$pdf->Cell(100,5,'',0,0);
$pdf->Cell(100,5,'',0,1);
$pdf->Cell(100,5,'Gerente Administrativo',0,0,'C');
$pdf->Cell(100,5,'Testigo',0,1,'C');
$pdf->SetXY(10,210);
$pdf->Ln();


$pdfdoc=$pdf->Output('Custodia.pdf', 'D');//PARA DESCARGAR EN PC



} else {
  header('Location: ../index.php');
}
?>

The idea is that I generate the PDF and at the moment of executing it says "There is no data in the Database" being that if the registration number is kept active and continues until I close the window. Thanks.

    
asked by Juan Pablo Bustamante Luna 10.02.2017 в 18:17
source

2 answers

2
  

If the problem is the file download then it is better not to control the download.

When you wanted to download a file but did not want the typical file download one had to do a trick, play with HTML Iframes , where you generated dynamic you applied some styles and assigned a path so you can download it backgroung a file. But what was the problem, that you could not detect if there was an error with the download, as if to control the message of descargando... . Then I found an alternative that simplified my problem. jQuery File Download Plugin for Ajax

Solution to your problem: Straight to the code, just fit what you need.

I made 3 files:

  • formulario1.php: That you will have the example of using the download plugin.
  • returnFile.php: For the example I propose, just download an image, in your case, make it suitable for a PDF file.
  • formular2.php: They have nothing of content, it was only for running tests.

formulario1.php:

<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/ui-lightness/jquery-ui.css" rel="stylesheet" type="text/css" />
  <link href="http://jqueryfiledownload.apphb.com/Content/Site.css" rel="stylesheet" type="text/css" />

  <!--jquery.fileDownload.js -->
  <script src="http://jqueryfiledownload.apphb.com/Scripts/jquery.fileDownload.js" type="text/javascript"></script>
</head>

<body>
  <h5>FORMULARIO 1</h5>
  <input type="button" id="btnDescargarNormal" value="Normal">
  <input type="button" id="btnDescargarError" value="Error">


  <!-- Sirve para indicar al usuario que se está realizando una descarga -->
  <div id="preparing-file-modal" title="Generando Reporte..." style="display: none;">
    Generando archivo, favor de esperar...
    <div class="ui-progressbar-value ui-corner-left ui-corner-right" style="width: 100%; height:22px; margin-top: 20px;"></div>
  </div>
  <div id="error-modal" title="Error" style="display: none;"></div>
  <!---->

  <script>
    (function() {

      var descargarArchivo = function(error) {
        var $preparingFileModal = $("#preparing-file-modal");

        $preparingFileModal.dialog({
          modal: true
        });

        var urlArchivo = 'devolverArchivo.php' + (error || '');

        $.fileDownload(urlArchivo, {
          successCallback: function(url) {
            //$preparingFileModal.dialog('close');
            location.href = 'formulario2.php';
          },
          failCallback: function(responseHtml, url) {
            $preparingFileModal.dialog('close');

            $("#error-modal").html(responseHtml).dialog({
              modal: true
            });
          }
        });
      }

      $('#btnDescargarNormal').on('click', function(e) {
        descargarArchivo(null);
      });

      $('#btnDescargarError').on('click', function(e) {
        descargarArchivo('?error=error');
      });

    })();
  </script>

</body>

</html>

returnFile.php:

<?php
// Verificar parametro

if(isset($_GET["error"])){
    // Establecer error detectado
    header('Set-Cookie: fileDownload=false; path=/');
    header('Content-Type: text/html; charset=utf-8');
    echo '<h5>No existen datos en la Base de Datos</h5>';
}
else{

    // Establecer el tipo de contenido, para el ejemplo yo considero una imagen
    header('Set-Cookie: fileDownload=true; path=/');
    header('Cache-Control: max-age=60, must-revalidate');
    header('Content-Type: image/png');
    header('Content-Disposition: attachment; filename="archivoGenerado.png"');

    $im = imagecreatetruecolor(400, 30);
    $blanco = imagecolorallocate($im, 255, 255, 255);
    $gris = imagecolorallocate($im, 128, 128, 128);
    $negro = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 399, 29, $blanco);
    $texto = '¡Bienvenido a SOes!';
    $fuente = 'arial.ttf';
    imagettftext($im, 20, 0, 11, 21, $gris, $fuente, $texto);
    imagettftext($im, 20, 0, 10, 20, $negro, $fuente, $texto);
    imagepng($im);
    imagedestroy($im);
}

?>

Tests Screenshots of the behavior when it exists and not error.

No Error

With Error

I hope I have solved your problem.

    
answered by 20.02.2017 / 03:33
source
0

As I see it, you have some conceptual problems when you try to download. According to your code:

<p>Descargar PDF:
    <a href="verificar.view.php" class="btn btn-info btn-lg" id="imprime">
        <span class="glyphicon glyphicon-download-alt"></span> Descargar
    </a>
    <script>
    $(function () {
        $('#imprime').on('click', function () {
            var last_id = $(this).data().last_id;
            $.post( 'verifica.view.php', { last_id: last_id } );
        });
    });

    </script>
</p>

You make an AJAX request (XHR, to use the correct terms), using POST with the id of the generated PDF. The problem is that this XHR is only called in the background and you do not control the response of this request anywhere, that is why despite generating the PDF correctly, you can not see it.

Also, when you say:

  

at the time of executing, it says "There is no data in the Database" being that if the registration number is registered and is still active until I close the window.

I assume that you are opening the URL in a new tab, but according to your code, the id of the record is retrieved by POST ( $ultimo_registro=isset($_POST['last_id']); ), which is why it does not work when you open the tab.

By way of solution I can think of the following:

<p>Descargar PDF:
    <a href="verificar.view.php" class="btn btn-info btn-lg" target="_blank" id="imprime">
        <span class="glyphicon glyphicon-download-alt"></span> Descargar
    </a>
    <script>
    $(function () {
        $('#imprime').on('click', function () {
            var last_id = $(this).data().last_id;

            this.href = "verificar.view.php?last_id=" + last_id;
        });
    });

    </script>
</p>
                                    
answered by 14.02.2017 в 10:51