Home > OS >  Transform GET request to POST request to load generated PDF file
Transform GET request to POST request to load generated PDF file

Time:03-12

In an html page I have a button that loads a generated pdf:

<button onclick='getpdf()'>GET PDF</button>

<script>
function getpdf(){
  data={
    var1: 'var1',
    var2: 'var2'
  };
  window.open('genpdf.php?var1=' data['var1'] '&var2=' data['var2'], '_new');
}
</script>

genpdf.php is something like this:

<?php
require('fpdf/fpdf.php');

$var1 = $_GET['var1'];
$var2 = $_GET['var2'];

$pdf = new PDF();

/* ......... */

$pdf->Output('D','generated.pdf');
?>

My question is:

How can I change my code to pass parameters with POST method?

SOLUTION

ADyson suggested me this solution:

<form id="pdf" action="genpdf.php" methon="POST" target="_new">
  <input type="hidden" name="var1" />
  <input type="hidden" name="var2" />
  <button onclick='getpdf()'>GET PDF</button>
</form>

<script>
function getpdf(){
  $("#pdf input[name=var1]").val('var1');
  $("#pdf input[name=var2]").val('var2');
  $("#pdf").submit();
}
</script>

and

<?php
require('fpdf/fpdf.php');

$var1 = $_POST['var1'];
$var2 = $_POST['var2'];

$pdf = new PDF();

/* ......... */

$pdf->Output('D','generated.pdf');
?>

and it works fine!

BUT

If I wanted to do that without the use of a form, how could I do?

CodePudding user response:

If you want to implement without coding HTML then use following Javascript

var myform = document.createElement('form');
myform.style.display = "none";
myform.name='PdfGenOrSomethingElse';
myform.method='POST';
myform.action='genpdf.php';
myform.target='_blank';

var var1=document.createElement('input');
var1.type='text';
var1.name='var1';
var1.value='Put/update your value';

var var2=document.createElement('input');
var2.type='text';
var2.name='var2';
var2.value='Put/update your value';

myform.appendChild(var1);
myform.appendChild(var2);

document.body.appendChild(myform);
myform.submit();

Notice the form will not be displayed on the page. "display" property is set to "none".

CodePudding user response:

You don't need any javascript function for this. Just use FORM element with action post:

<form action="genpdf.php" method="post" target="_blank">

    <input type="text" name="var1" value="" />
    <input type="text" name="var2" value="" />

    <button type="submit ">GET PDF</button>
</form>

The don't forget to use $_POST instead of $_GET in your PHP script.

  • Related