将JSON传递给PHP以写入文件时出错

时间:2017-01-06 01:09:49

标签: javascript php json ajax

好的,所以我花了几个小时研究解决方案,但没有人解决这个问题。我认为这是一个愚蠢的东西,但我对PHP很新,所以我很抱歉,如果我只是遗漏了一些小东西。我在index.php文件中有一个表单,当单击保存按钮时,表单数据被收集并制作成JSON,然后传递给PHP文件以写入文件并下载。我已经测试了我能想到的东西。当我在json上调用gettype时,返回的类型是字符串,所以当我把它写入文件时,我不确定为什么没有显示。如果我通过调用fwrite($fh, "some text")来写文件,它会显示在文件中。我仍然生成PHP Notice: Undefined index: myData in /var/www/html/UTSAForm/php/save.php on line 4的错误,虽然我不明白为什么,因为我看到了多个代码片段,其中ajax请求的格式相同。代码如下:

HTML:

<div class="top_bar">
        <button type="button" class="btn btn-success btn-md" onclick="save();" >Save</button>
        <button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#openModal">
          Open
        </button>
    </div>
<div class="form">
        <div class="form-group">
            <label>Reivew Period</label>
            <label for="review_period_from">From</label>
            <input type="text" name="review_period_from" id="review_period_from">
            <label for="review_period_to">To</label>
            <input type="text" name="review_period_to" id="review_period_to">
        </div>
        <div class="form-group">
            <label for="employee_name">Name</label>
            <input type="text" clsas="form-control" id="employee_name" placeholder="Employee Name">
            <label for="employee_title">Title</label>
            <input type="text" clsas="form-control" id="employee_title" placeholder="Employee Title">
            <label for="employee_id">EMPL ID</label>
            <input type="text" clsas="form-control" id="employee_id" placeholder="Employee ID">
            <label for="job_code">Job Code</label>
            <input type="text" clsas="form-control" id="job_code" placeholder="Job Code">
        </div>
    </div>

JS:

function save(){
    createJSON();
    // var jsonString = JSON.stringify(jsonObj);
    // console.log(jsonString);
    $.ajax({
        type: 'POST',
        url: 'php/save.php',
        data: {'myData':JSON.stringify(jsonObj)},
        cache: false,
        success: function(data){
            // console.log(data);
            window.location = 'php/save.php';
        },
        error: function(){
            alert("Failed to save file");
        }
    });
}

function createJSON(){
jsonObj = [];

$('.form input').each(function(){
    var field = this.id;
    var input = $(this).val();

    item = {};
    item ["field"] = field;
    item ["input"] = input;

    jsonObj.push(item);
});

}

PHP:

<?php
$file = "formData.txt";
$fh = fopen($file, "w"); 
$json = $_POST['myData'];
fwrite($fh, $json);

// set the headers, so that
// the browser knows to expect a .txt file download.
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Type: text/html");
header("Content-Length: " . filesize($file));

// set Cache headers, to minimize the
// risk of the browser using old versions of the data.
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate");

// print out the file data for
// the browser to open or save.
readfile($file);

exit;

&GT;

更新:

固定,至少它是功能性的,不确定它是否仍然是实现所需结果的正确方法。感谢@ nishanth-matha。修正了以下代码:

JS(Ajax调用)

    function save(){
    createJSON();
    // console.log(jsonObj);
    // var jsonString = JSON.stringify(jsonObj);
    // console.log(jsonString);
    $.ajax({
        type: 'POST',
        url: 'php/save.php',
        data: {'myData':JSON.stringify(jsonObj)},
        cache: false,
        success: function(data){
            // console.log(data);
            window.location = 'php/downloadData.php';
        },
        error: function(){
            alert("Failed to save file");
        }
    });
}

PHP save.php

<?php
$json = $_POST['myData'];
if(json_decode($json) != null){
    // echo "valid json";
    $file = "formData.txt";
    $fh = fopen($file, "w"); 
    fwrite($fh, $json);
    fclose($fh);

    exit;
}else{
    echo "Invalid json";
}

&GT;

PHP downloadData.php

<?php
    // echo "valid json";
    $file = "formData.txt";

    // set the headers, so that
    // the browser knows to expect a .txt file download.
    header("Content-Disposition: attachment; filename=".basename($file));
    header("Content-Type: text/html");
    header("Content-Length: " . filesize($file));

    // set Cache headers, to minimize the
    // risk of the browser using old versions of the data.
    header("Pragma: no-cache");
    header("Expires: 0");
    header("Cache-Control: must-revalidate");

    // print out the file data for
    // the browser to open or save.
    readfile($file);

    exit;

&GT;

2 个答案:

答案 0 :(得分:0)

我认为错误发生在你的JS中:

首先,您的错误PHP Notice: Undefined index: myData in /var/www/html/UTSAForm/php/save.php on line 4是由于您在save.php功能中重定向到ajax success而导致的。由于你的php再次运行save.php脚本而发现POST变量myDATA不再可用,因为你只是重定向网址而不发布任何内容。

其次,您的ajax调用中未定义jsonObj。我想你要从createJSON返回一个值并在ajax调用中使用它,如果是这样,你需要执行以下操作:

function save(){
    var jsonObj = createJSON();
    // var jsonString = JSON.stringify(jsonObj);
    // console.log(jsonString);
    $.ajax({
        type: 'POST',
        url: 'php/save.php',
        data: {'myData':JSON.stringify(jsonObj)},
        cache: false,
        success: function(data){
            console.log(data);
            $('#result').html(data);
            //window.location = 'php/save.php';
        },
        error: function(){
            alert("Failed to save file");
        }
    });
}

function createJSON(){
  jsonObj = [];

  $('.form input').each(function(){
    var field = this.id;
    var input = $(this).val();

    item = {};
    item ["field"] = field;
    item ["input"] = input;

    jsonObj.push(item);
  });
  return jsonObj;
}

在HTML中添加以下行:

<div class="result"></div>

在PHP中:

<?php
try{
$file = "formData.txt";
$fh = fopen($file, "w"); 
$json = $_POST['myData'];
fwrite($fh, $json);

// set the headers, so that
// the browser knows to expect a .txt file download.
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Type: text/html");
header("Content-Length: " . filesize($file));

// set Cache headers, to minimize the
// risk of the browser using old versions of the data.
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate");

// print out the file data for
// the browser to open or save.
readfile($file);
echo "Successfully downloaded"

} catch (Exception $e) {
  echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    exit;
}

答案 1 :(得分:0)

你可以在你的Javascript中将jsonObj = [];定义为全局变量,它就可以了,就像这样:

jsonObj = [];

function save(){
    createJSON();
    // var jsonString = JSON.stringify(jsonObj);
    // console.log(jsonString);
    $.ajax({
        type: 'POST',
        url: 'php/save.php',
        data: {'myData':JSON.stringify(jsonObj)},
        cache: false,
        success: function(data){
           // console.log(data);
            window.location = 'php/save.php';
        },
        error: function(){
            alert("Failed to save file");
        }
    });
 }

function createJSON(){

    $('.form input').each(function(){
        var field = this.id;
        var input = $(this).val();

        item = {};
        item ["field"] = field;
        item ["input"] = input;

        jsonObj.push(item);
     });
}