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.