rkbom9
rkbom9

Reputation: 913

pass localStorage value into php

I have a page which generates a chart. I have a button which generates a pdf report for it. I wanted to create an image of this chart and insert it into the pdf. To create the image, I use html2canvas and get the dataurl which I store in the localstorage.

chart.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">
   $(document).ready(function() {
        $('#download').click(function() {
             $.ajax({
                type: "POST",
                url: "pdfGen.php",
                data: 'hello',
                success: function(data) {
                    alert("hi");
                }
              });
         });
   }); //END $(document).ready()
</script>

<script>
  //<![CDATA[
  (function() {
     window.onload = function(){
         html2canvas(document.getElementById('chart'), {
              "onrendered": function(canvas) {
                   var img = new Image();
                   img.onload = function() {
                       img.onload = null;
                       console.log(canvas.toDataURL("image/png"));
                       window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
                   };
                   img.onerror = function() {
                       img.onerror = null;
                       if(window.console.log) {
                           window.console.log("Not loaded image from canvas.toDataURL");
                       } else {
                           //alert("Not loaded image from canvas.toDataURL");
                       }
                   };
                   img.src = canvas.toDataURL("image/png");
               }
            });
         };
     })();
//]]>
</script>    
<body>
   <a href="pdfGen.php" id="download" class="button">Report</a> 
   ..more code to generate the chart
</body>

The download button calls the pdfGen.php script which uses fpdf to generate a report. pdfGen.php

<?php
    echo $_POST['data']; //gives error
    /*$pdf = new FPDF();
    $pdf->AddPage();

    //over here I want to add the image from the chart.php page whose data url is now in the localstorage.
    ..more code to generate report
    $pdf->output();*/
 ?>

How do I get the image inside the php script? I try to make the ajax call but I get undefined index data in pdfGen.php script. I got the alert HI but could not get the data on the server. It does not seem to work.

Upvotes: 2

Views: 10698

Answers (2)

Steffan
Steffan

Reputation: 733

Here is an example passing localstorage from js to php session, assume using jQuery as ajax requester.

Handle

In root, add file: retrieve.php (This will RETRIEVE AND SYNC localstorage from js with session from php)

<?php

session_start();
$key = 'my-car'; // Your localstorage key
$client = (isset($_GET[$key]) && $_GET[$key] !== 'null') ? $_GET[$key] : null;
$server = isset($_SESSION[$key]) ? $_SESSION[$key] : null;
$_SESSION[$key] = $client; // Now stored in php´s session variable $_SESSION['my-car']

echo $client === $server ? 'true' : 'false'; // Tells js to reload if data was not synced

Set

In your index.html / index.php add this script: (This will PASS localstorage to php and reload if not synced after php´s session data is set)

<?php
  session_start(); // Dont forget this line
  $key = 'my-car';
  if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
     $car = json_decode($_SESSION[$key], true);
     echo $car['name']; // Will print 'Tesla'
  }
?>
<script>
  // Set in JS
  var key = '<?php echo $key; ?>';
  window.localStorage.setItem(key, JSON.stringify({
    name: 'Tesla'
  })); // Set to whatever you want
  var data = {};
  data[key] = window.localStorage.getItem(key);
  // Passes to PHP using GET
  jQuery.get(
    location.protocol + '//' + location.host + '/retrieve.php',
    data
  ).done(function (synced) {
    if (synced !== 'true') {
      // If not synced, reload
      location.reload();
      // Caution! If it doesnt sync correctly, infinite loop may occure
    }
  });
</script>

Use

And last, passing session from PHP to localstorage in js ->

In ANY php file:

<?php

start_session();
$key = 'my-car';

if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
   // Print old value
   $car = json_decode($_SESSION[$key], true);
   echo $car['name']; // 'Tesla'

   // Update object
   $car['name'] = 'Honda';
   $_SESSION[$key] = json_encode($car);

   // Pass to js:
   echo "<script>window.localStorage.setItem('" . $key . "', '" . $_SESSION[$key] . "');</script>";

   // Prints the updated object with name 'Honda'
   echo "<script>console.log(window.localStorage.getItem('" . $key . "'))";
 }

Note: 'my-car' can be replaced with your own keys.

Upvotes: 0

Mangesh Parte
Mangesh Parte

Reputation: 2177

Your ajax call is wrong.

Your call should be like this to get value hello in data variable/key

$('#download').click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "pdfGen.php",
       data: 'data=hello',
       success: function(data) {
           alert("hi");
       }
   });
});

To learn more about the jQuery Ajax refer this link.

Upvotes: 1

Related Questions