私は解決策を研究するのに数時間を費やしましたが、問題の解決には時間がかかりませんでした。私はそれが何かばかげていると思いますが、私は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リクエストが同じ方法でフォーマットされた複数のコードスニペットを見たのはなぜですか?エラーPHPにJSONを渡してファイルに書き込む
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;
>
を次のようにコードがあります更新:
固定されていても、少なくとも機能していて、依然として望ましい結果を得るための適切な方法であるかどうかは不明です。しかし、@ 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";
}
>
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;
?
?>
あなたは 'jsonObj = [];'をcreateJSON()スコープの中で定義しています。次に、保存時にグローバル変数として参照しようとしています。それは動作しません。まず、グローバル変数として 'jsonObj []'を定義します。 – MarkSkayff
@ MarkSkayff私は今、コードを見て、jsonObj変数がグローバルでアクセス可能であってはならないことを知っているので、なぜそれがわからないのですか?私はそれをグローバルにして、なぜ明らかにそうであってはならないときにそれがなぜ働いているかを後で把握できるかどうかを見ます。 –
グローバルであれば問題ありません。グローバル変数も関数内で見ることができます。 – MarkSkayff