0

I tried to send the data in localstorage to php with ajax but I get the error of

undefined index data

The code generate a dataurl which is stored in the localstorage. When the user click on the link the pdfGen.php is called where I want to use the data in localstrage.

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: {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" >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 data inside the php script? I try to make the ajax call but I get undefined index in pdfGen.php script. I got the alert HI but could not get the data on the server. It does not seem to work.

rkbom9
  • 913
  • 3
  • 9
  • 17

2 Answers2

2

In your ajax define data like this:

$.ajax({
                type: "POST",
                url: "pdfGen.php",
                data: { data: 'hello' },
                success: function(data) {
                    alert("hi");
                }
        });

now you can retrieve it via $_POST["data"]. Seems you need to read more about jquery ajax documentation, read it here friend http://api.jquery.com/jquery.ajax/.

"data" element in ajax is your parameters

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

see the bold texts from jquery ajax documentation.

EDIT

Found the second error, its your link, you are doing ajax and then the link also redirects to pdfGen.php because of href, to prevent this you can make the href "#", or you could use preventdefault():

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

SECOND EDIT

Seems like you need to redirect to pdfGen.php to get the reports, then you might don't need an ajax, what you should do is put the parameter to your link href.

<a href="pdfGen.php?data=hello" id="download" >Report</a>

and get it via $_GET["data"]; in php.

VMcreator
  • 833
  • 8
  • 17
  • actually it still doesnt work. I get the same error. I already tried to sending as a key/value json like data but still does nt work – rkbom9 Aug 04 '15 at 04:17
  • Hmmm.. thats weird, have you try the $.post() method? try using that, and I'll find out why above code fails. – VMcreator Aug 04 '15 at 04:31
  • yes it fails same error did $.post("pdfGen.php", { data: "hello" }, function(data){ }); – rkbom9 Aug 04 '15 at 04:39
  • I was thinking of the same issue. So i tried it and it makes a succeeful post request but nothing gets printed. It stays on the same chart.php page instead of printing the data in a new page. – rkbom9 Aug 04 '15 at 05:11
  • Okay, it seems like you need to save the pdf created by fpdf and return the file name. – VMcreator Aug 04 '15 at 05:12
  • so how do i get the data in a php variable ? – rkbom9 Aug 04 '15 at 05:15
  • You need only it pass it via href. – VMcreator Aug 04 '15 at 05:17
  • hey @VMcreator so this enable me this pass data but the data that I am passing is a image dataURI which is so large that it goes beyond url capacity. I have created another qeuestion for that http://stackoverflow.com/questions/31801548/how-to-pass-image-data-uri-from-javascript-to-php – rkbom9 Aug 04 '15 at 06:10
  • If you could help with this it would be really greatful. I been spending hours becuz of this – rkbom9 Aug 04 '15 at 06:11
1

Your error is because you are directing back to pdfGen.php using anchor tag. Ajax request will send the data and receive the response in success function. When you are using <a href="pdfGen.php" id="download" >Report</a> you are actually going back to pdfGen.php without any value in $_POST['data'].

Ajax Call is as below:

var toSend = "data:"+jsVariableContainingYourText; (or simply "data:Hello";)
$.ajax({
          type: "POST",
          url: "pdfGen.php",
          data: toSend,
          success: function(data) 
          {
                  alert("hi");
          }
      });

In pfdGen.php, As a good programming practice, you should also check if the post variable is set or not.

if(isset($_POST['data'])
{  //do something  }
else
{ //appropriate message }

Also make sure that url for ajax call is correct (In your case, pdfGen.php should be in the same folder as your html file)

  • it goes in the else condition which should not happen. So it means the data wasnot available as post which is wierd even though we made a post ajax call – rkbom9 Aug 04 '15 at 04:56