2017-01-06 9 views
0

私は解決策を研究するのに数時間を費やしましたが、問題の解決には時間がかかりませんでした。私はそれが何かばかげていると思いますが、私は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; 

?>

+0

あなたは 'jsonObj = [];'をcreateJSON()スコープの中で定義しています。次に、保存時にグローバル変数として参照しようとしています。それは動作しません。まず、グローバル変数として 'jsonObj []'を定義します。 – MarkSkayff

+0

@ MarkSkayff私は今、コードを見て、jsonObj変数がグローバルでアクセス可能であってはならないことを知っているので、なぜそれがわからないのですか?私はそれをグローバルにして、なぜ明らかにそうであってはならないときにそれがなぜ働いているかを後で把握できるかどうかを見ます。 –

+0

グローバルであれば問題ありません。グローバル変数も関数内で見ることができます。 – MarkSkayff

答えて

0

私は、エラーがあなたのJSであると思う:まず

、あなたのエラーPHP Notice: Undefined index: myData in /var/www/html/UTSAForm/php/save.php on line 4はあなたajax success機能にしようとしているsave.phpにリダイレクトするためです。そのためあなたのPHPはsave.phpスクリプトを再度実行するだけで、POST変数myDATAは、何も投稿していないURLをリダイレクトしているので、もう利用できません。

第2に、jsonObjはあなたのajax呼び出しでは定義されていません。私はあなたが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でこの行を追加します。PHPで

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

を:

<?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; 
} 
+0

JSはグローバルです。 jsonObj変数をsave関数でテストしましたが、正しいです。また、PHPファイル内の$ json変数をテストし、変数の内容をエコーバックしました。 save.phpファイル$ JSONは、gettype()関数が正しく戻ると仮定してJSONを表す文字列です。 –

+0

は私の編集 –

+0

素晴らしいを参照してください。本当にありがとう。今、完璧な意味合いがあります。私はそれを正しい方法で修正したかどうかはわかりませんが、ファイルを書き、ファイルを2つの別々のファイルにダウンロードするというロジックを分割しました。そのため、ajax呼び出しはJSONを送信してファイルに書き込み、成功関数はPHPスクリプトを呼び出してダウンロードします。 –

0

あなたはあなたのJavaScriptでグローバルVARとして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); 
    }); 
} 
関連する問題