简体   繁体   English

ajax从localstorage发送数据到php

[英]ajax send data to php from localstorage

I tried to send the data in localstorage to php with ajax but I get the error of 我尝试使用ajax将localstorage中的数据发送到php,但出现以下错误

undefined index data

The code generate a dataurl which is stored in the localstorage. 该代码生成一个dataurl,该URL存储在本地存储中。 When the user click on the link the pdfGen.php is called where I want to use the data in localstrage. 当用户单击链接时,将在我要在localstrage中使用数据的位置调用pdfGen.php。

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脚本,该脚本使用fpdf生成报告。

pdfGen.php 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? 我如何在php脚本中获取数据? I try to make the ajax call but I get undefined index in pdfGen.php script. 我尝试进行ajax调用,但在pdfGen.php脚本中得到未定义的索引。 I got the alert HI but could not get the data on the server. 我收到警报HI,但无法获取服务器上的数据。 It does not seem to work. 它似乎不起作用。

In your ajax define data like this: 在您的ajax中定义如下数据:

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

now you can retrieve it via $_POST["data"]. 现在您可以通过$ _POST [“ data”]检索它。 Seems you need to read more about jquery ajax documentation, read it here friend http://api.jquery.com/jquery.ajax/ . 似乎您需要阅读有关jquery ajax文档的更多信息,请在此处阅读,朋友http://api.jquery.com/jquery.ajax/

"data" element in ajax is your parameters ajax中的“数据”元素是您的参数

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. 它被附加到GET请求的URL上。 See processData option to prevent this automatic processing. 请参阅processData选项以防止这种自动处理。 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). 如果value是一个Array,则jQuery会根据传统设置(如下所述)的值,使用相同的键序列化多个值。

see the bold texts from jquery ajax documentation. 请参阅jquery ajax文档中的粗体文本。

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(): 找到第二个错误,它是您的链接,您正在执行ajax,然后该链接也由于href而重定向到pdfGen.php,为防止这种情况,您可以将href设置为“#”,也可以使用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. 似乎您需要重定向到pdfGen.php来获取报告,然后您可能不需要ajax,您应该做的就是将参数放在链接href中。

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

and get it via $_GET["data"]; 并通过$ _GET [“ data”]来获取它; in php. 在PHP中。

Your error is because you are directing back to pdfGen.php using anchor tag. 您的错误是因为您正在使用定位标记重定向回pdfGen.php。 Ajax request will send the data and receive the response in success function. Ajax请求将在成功功能中发送数据并接收响应。 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']. 当您使用<a href="pdfGen.php" id="download" >Report</a>时,实际上您将返回pdfGen.php,而$ _POST ['data']中没有任何值。

Ajax Call is as below: Ajax调用如下:

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. 在pfdGen.php中,作为一种好的编程习惯,您还应该检查post变量是否已设置。

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) 还要确保ajax调用的URL是正确的(在您的情况下,pdfGen.php应该与您的html文件位于同一文件夹中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM