简体   繁体   English

PHP创建的图像文件json_encode返回SyntaxError:JSON.parse:数据意外结束

[英]PHP created image file json_encode is returning SyntaxError: JSON.parse: unexpected end of data

First time poster, be gentle. 第一次张贴海报时,请保持温柔。 Anyway I'll try and make this as clear as possible. 无论如何,我会尽力使这一点尽可能清楚。

I have a site that uses a combination of jQuery/Ajax and PHP to create offer 'coupons'. 我有一个结合使用jQuery / Ajax和PHP来创建商品“优惠券”的网站。 When a user visits, they select the coupons they want to buy (via PayPal) and submit. 用户访问时,他们选择要购买的优惠券(通过PayPal)并提交。 I'm sending this to paypal and listening for the IPN within my PHP script and in the case of a Valid IPN the script should proceed to assign a randomly generated 12 digit 'barcode' to the coupons they chose, add them all to a file that is opened for printing. 我将其发送给贝宝,并在我的PHP脚本中侦听IPN,如果是有效IPN,则脚本应继续为他们选择的优惠券分配一个随机生成的12位数字“条形码”,并将其全部添加到文件中打开进行打印。 I'm storing the selected coupon data (name array) using this jQuery plugin 我正在使用此jQuery插件存储选定的优惠券数据(名称数组)

The initial coupon generation works, the paypal integration (including the IPN listener) works. 最初的优惠券生成有效,贝宝集成(包括IPN侦听器)有效。 I can see the cookies in the console while I'm testing this so my form data is there. 在测试时,我可以在控制台中看到cookie,因此表单数据在那里。 I'm even getting the 'success' portion of the json array. 我什至得到json数组的“成功”部分。

My issues is that I'm trying to fetch the image file via ajax but I am getting 'SyntaxError: JSON.parse: unexpected end of data' and I can't figure out why. 我的问题是我试图通过Ajax来获取图像文件,但是却收到“ SyntaxError:JSON.parse:意外的数据结尾”,我不知道为什么。 The image creation code was already written prior to me taking this on, I just needed to tie it together with paypal. 在我进行此操作之前已经编写了图像创建代码,我只需要将其与Paypal捆绑在一起即可。



my-offers.php my-offers.php

$(window).load(function(){

  var extradata = {};
  extradata.action = 'createCoupon';
  extradata.offers = $.cookies.get("offers");
  console.log(extradata);
    $.ajax({
      url: 'api/data_request.php',
      success: function(e, data, result){
          console.log('done!', data);   
              //this returns 'success' but console.log('done!', e) returns empty string

        //below is throwing unexpected end of data
        var resultObj = JSON.parse(e);
                        if(resultObj.result === 'success'){
                            //console.log('success!'+resultObj);
                            window.open(resultsObj.filename, '_blank');
                        }else{
                            console.log('some sort of error!', data);
                        }
                    },
                    type: 'POST',
                    data: extradata,
                    error: function(e, data, extra){
                            console.log('there was a serious error!', e, data, extra);
                            console.log(data.errorThrown, data.textStatus, data.jqXHR);
                    }                       
                });



data-request.php data-request.php

//go through finished coupons array, and put them all on one image
            //then save the image in coupons
            $finalimg = imagecreatetruecolor($thewidth, $theheight);
            $cursor = 0;
            for($i = 0; $i<4; $i++){
                $obj = $finishedCoupons[$i];
                $coupon = $obj[0];
                $width = $obj[1];
                $height = $obj[2];
                $copyied = imagecopymerge($finalimg, $coupon, 0, $cursor, 0, 0, $width, $height, 100); 
                if($copyied === false){
                    returnError('error copying images');
                }
                $cursor = $cursor+$height;
            }
            $didit = imagejpeg($finalimg, '/images/coupons/'.$thefilename.'.jpg', 100);
            if($didit === false){
                returnError('final copying error'.$thefilename);
            }else{


                echo json_encode(array('result'=>'success', 'filename'=>'images/coupons/'.$thefilename.'.jpg'));
                die();

            }



MySQL select the coupons and create barcodes (for context) MySQL选择优惠券并创建条形码(针对上下文)

//get the coupon picture we'll put the numbers on
                    $success1 = $mysqli->prepare("SELECT title, text, realcoupon FROM offers WHERE offer_id = ? LIMIT 1");
                    $success1->bind_param('i', $coupon);
                    $success1->execute();
                    $success1->store_result();
                    $success1->bind_result($title, $text, $source);
                    $success1->fetch();                 
                //now actually generate the numbers
                //perform database collision detection
                //number is 12 digits long so we can use it in a barcode if needed
                    $exists = 1;
                       while($exists !== 0){ 
                        $code = generateRandomNumber();
                        $success1 = $mysqli->prepare("SELECT barcode FROM offerId WHERE barcode = ?");
                        $success1->bind_param('s', $code);
                        $success1->execute();
                        $success1->store_result();
                        $exists = $success1->num_rows;
                       }
                    $thefilename.=$code;
                //$code is a unique barcode now, so we should insert it into the array
                // coupon contains the offer_id
                $success = $mysqli->prepare("INSERT INTO offerId (offer_id, barcode, date) VALUES (?, ?, CURRENT_TIMESTAMP)");
                $success->bind_param('is', $coupon, $code);
                $success->execute();
                //$success->store_result();
                //$success->fetch();
                $affected = $success->affected_rows;
                if($affected !== 1){
                    returnError($affected);
                    returnError('Error inserting the barcode!');
                }                   
                //now put the numbers on the coupon and push it to the finishedCoupons array
                $source = '../images/'.$source;
                try{
                   $extension = pathinfo($source, PATHINFO_EXTENSION);
                   if(!file_exists($source)){
                    returnError('Cant find coupon!');
                    return false;
                   }
                   $info = getimagesize($source);
                   if($info === false){
                      returnError("InvalidImage");
                      return false;
                   }
                }catch (Exception $e){
                    returnError("InvalidImage");
                    return false;
                }
                $type    = $info[2];
                $width   = $info[0]; // you don't need to use the imagesx and imagesy functions
                $height  = $info[1];
                if($width>$thewidth){
                    $thewidth = $width;
                }

I've tried setting the php file to header('Content-type: application/json'); 我试图将php文件设置为header('Content-type:application / json'); I've tried calling dataType: 'json' in my ajax call. 我已经尝试在ajax调用中调用dataType:'json'。 I've even run php -l data_request.php to check for syntax errors and nothing was returend. 我什至运行了php -l data_request.php来检查语法错误,并且没有任何麻烦。 Nothing seems to work. 似乎没有任何作用。 This is the last step I need to debug!! 这是我需要调试的最后一步! I've been working on this for hours. 我已经为此工作了几个小时。

UPDATE: After inspecting the response header, it looks like it's being transferred as type text/html instead of text/json or application/json 更新:检查响应标头后,它看起来像是以text / html类型而不是text / json或application / json类型传输

The last line of your PHP is the problem: PHP的最后一行是问题:

echo json_encode(array('result'=>'success', 
                       'filename'=>'images/coupons/'.$thefilename.'.jpg'));
die(); echo $coupons;

When you write PHP services, you should only be echo'ing the JSON nothing else, or the JSON response data won't be valid since it is being concatenated with another string. 编写PHP服务时,应仅回显JSON,否则JSON响应数据将无效,因为它与另一个字符串连接在一起。

You must echo JSON ONLY : 您必须回显JSON

echo json_encode(array('result'=>'success', 
                       'filename'=>'images/coupons/'.$thefilename.'.jpg'));
die(); //echo $coupons;

Found the issue. 找到了问题。

IPN is not real time, and since the client here needed to interrupt the payment flow here in the case that the payment (ipn) failed, this didn't work, which in turn caused the JSON to be partially empty since it was wrapped in an if() with the paypal IPN. IPN不是实时的,并且由于在付款(ipn)失败的情况下,此处的客户端需要在此处中断付款流程,因此此操作不起作用,这又由于将JSON包装在其中而导致JSON部分为空一个带有贝宝IPN的if()。 So I changed this out with paypal PDT (payment data transfer) which is instant, and then verified against the transaction id and payment amount. 因此,我使用即时的Paypal PDT(付款数据传输)更改了此设置,然后针对交易ID和付款金额进行了验证。

暂无
暂无

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

相关问题 json_encode和JSON.parse错误:SyntaxError:JSON.parse:JSON数据后第2行第43列的JSON数据后出现意外的非空白字符 - json_encode and JSON.parse error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 43 of the JSON data Ajax拒绝PHP通过“ SyntaxError:JSON.parse:JSON数据的第1行第1列出现意外字符”创建的JSON - Ajax rejecting JSON created by PHP with “SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data” 解析由php json_encode创建的JSON数据 - Parse JSON data created by php json_encode 来自 php 的 json_encode 问题的 JSON.parse - JSON.parse from php's json_encode issue PHP json_encode与JAVASCRIPT JSON.parse - PHP json_encode versus JAVASCRIPT JSON.parse 在 javascript 中使用 JSON.parse 对数据进行 Json_encode - Json_encode data using JSON.parse in javascript 带有json_encode和html的JSON.parse - JSON.parse with json_encode and html 在PHP中使用json_encode()和JavaScript中的JSON.parse()来读取/写入文件 - Using json_encode() in PHP and JSON.parse() in JavaScript to read/write from/to a file SyntaxError: JSON.parse: JSON 数据第 1 行第 1 列的数据意外结束 OK - SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data OK 在我的 API 请求中获取“SyntaxError: ”JSON.parse: unexpected end of data at the line 1 column 1 of the JSON data” - Getting “SyntaxError: ”JSON.parse: unexpected end of data at line 1 column 1 of the JSON data" on my API request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM