2016-12-08 8 views
0

私のPHPスクリプトにPOSTデータを送るのに苦労しているようです。POSTデータをPHPスクリプトに送信する - jQuery、AJAX&PHP

My AJAXはPHPスクリプトにデータ(ブログ投稿のID)を送信します。このスクリプトは、データベースと一致するIDを含む行を見つけます。

スクリプトは、ブログポストのタイトルとポストの内容を配列に返します。これは、AJAXがピックアップしてDOMのフォームに挿入します。

Iが正常にでき:

  • インサートサンプルデータ(例えば、私は単に私がAJAXに戻って通過していた配列に格納文字列は、それが正常形にこれらの文字列を挿入する場合)。
  • 静的IDが指定されている場合(たとえば、$ _POST ['editpostid']を切り替えて代わりに整数5を指定した場合など)、ID = 5の行が正常に検索され、 AJAXはこのデータをフォームに挿入します)。

したがって、私の観点から見ると、IDはPHPスクリプトに到達しない、またはJSONオブジェクト内のIDをスクリプトで見ることができないという問題があります。

私のコードを見て、あなたの考えを教えてください。私はこのすべてに慣れていないので、問題が解決したかどうか、あなたのフィードバックに感謝します。

Javascriptを/ jQueryの:

// When edit button is clicked 
$('li.edit').click(function() { 

    // Get class (postid inserted with PHP) of edit button, excluding edit class 
    var oldpostid = $(this).attr('class').split(' ')[1]; 

    alert(oldpostid); // Returns the correct postid, for example 5 

    var jsonObj = { 'postid': oldpostid }; 

    alert(jsonObj); // Returns 'object Object' 

    // Send postid to PHP script 
    $.ajax({ 
     type: 'POST', 
     url: '../scripts/fetchpost.php', 
     dataType: 'json', 
     data: { 'editpostid': jsonObj }, 
     success: function() { 

      // Fetch post data back from script 
      $.getJSON('../scripts/fetchpost.php', function(data) { 

       alert(data.title); // Returns null 
       alert(data.content); // Returns null 

       // All of the below code works if the PHP script returns sample text, 
       // or if an ID is specified in the PHP script itself 

       var title = data.title; 
       var content = data.content; 

       // Insert data into editor 
       $('#titlehead').text(title); 
       $('#edittitle').val(title); 
       var editor = 'editpost-content'; 
       tinymce.get(editor).setContent(content); 
      }); 
     }, 
     error: function(e) { 
     console.log(e.message); 
    } 
    }); 
}); 

PHP:

<?php 

// Specifies connection details 
include('../scripts/config.php'); 

// Fetch data from AJAX 
$postid = $_POST['editpostid']; // Where I think the problem lies. Returns null. 
// Again, this works if I switch out $_POST with an integer, such as 5 

// Find rows in database that match postid 
$postedit_qry = mysqli_query($dbconnect, "SELECT * FROM posts WHERE postid='$postid'"); 

// Store results in an associative array 
$row = mysqli_fetch_assoc($postedit_qry); 

// Split array into variables 
$title = $row['title']; 
$content = $row['content']; 

// Organise data into an array for json 
$postedit = array(
    'title' => $title, 
    'content' => $content 
); 

// Return array as json object for ajax to pick up 
echo json_encode($postedit); 

// Close connection 
mysqli_close($dbconnect); 

?> 

アップデート - ソリューション:

固定のjQuery/Javascriptを:

// Snip 

// Get class (postid inserted with PHP) of edit button, excluding edit class 
    var oldpostid = $(this).attr('class').split(' ')[1]; 

    // Send postid to PHP script 
    $.ajax({ 
     type: 'POST', 
     url: '../scripts/fetchpost.php', 
     dataType: 'json', 
     contentType: 'application/x-www-form-urlencoded', 
     data: { "editpostid": oldpostid }, 
     success: function(data) { 

      var title = data.title; 
      var content = data.content; 

// Snip 

PHPスクリプトは同じです。

ご協力いただきありがとうございます。 MrPupper

+0

すべての回答ありがとうございます!私は、FarzadとSpencerの両方の提案を組み合わせて使用​​しました。これには、PHPドキュメントを使用した私自身の研究も含まれます。私は解決策を含めるために私の元の質問を更新しました。 – MrPupper

答えて

0

コードを確認すると、fetchpost.phpスクリプトを2回要求しているため、nullが返っているようです。一度$.ajax(...);を介してスクリプトに連絡し、$.getJSON(...);に電話するともう一度。あなたは$.getJSON(...);経由で連絡を取ってもPOSTデータではないので、スクリプトにはGETリクエストを処理する方法が正しく定義されていないようですので、スクリプトはどのように反応するかを知らず、ヌル情報を返します。

私は次へのJavaScript/jQueryのを変更します

// When edit button is clicked 
$('li.edit').click(function() { 

    // Get class (postid inserted with PHP) of edit button, excluding edit class 
    var oldpostid = $(this).attr('class').split(' ')[1]; 

    alert(oldpostid); // Returns the correct postid, for example 5 

    var jsonObj = { 'postid': oldpostid }; 

    alert(jsonObj); // Returns 'object Object' 

    // Send postid to PHP script 
    $.ajax({ 
     type: 'POST', 
     url: '../scripts/fetchpost.php', 
     dataType: 'json', 
     data: {'editpostid': jsonObj }, 
     success: function(sData) { 
      var data = JSON.parse(sData); 
      alert(data.title); // Returns null 
      alert(data.content); // Returns null 

      // All of the below code works if the PHP script returns sample text, 
      // or if an ID is specified in the PHP script itself 

      var title = data.title; 
      var content = data.content; 

      // Insert data into editor 
      $('#titlehead').text(title); 
      $('#edittitle').val(title); 
      var editor = 'editpost-content'; 
      tinymce.get(editor).setContent(content); 
     }, 
     error: function(e) { 
      console.log(e.message); 
     } 
    }); 
}); 

また、PHPは$_POST[...]と対話できるようにapplication/x-www-form-urlencoded値を期待されようとしています。


;( the official PHP documentation for json_decode.を参照してください、 json_decodeの詳細について this answerにそれについての詳細を参照してください) $postedData = json_decode(file_get_contents('php://input'));:あなたはそれをJSONを、餌にしたい場合はこのようにして、その後、あなたのPHPには、次のようなソリューションを実装する必要があります。

注:質問の範囲外ですが、これを既に知っているかもしれませんが、postIdがされていないことを盲目的に信頼しているため、MySQLが安全でなくSQLインジェクションに対して脆弱であることを指摘することが重要です。改ざんされた$dbconnectを初期化してデータベースに接続した後、$postidをSQLクエリ文字列に入れる前に、$postid = $dbconnect->real_escape_string($postid);と言ってサニタイズする必要があります。

+0

多くのおかげでスペンサー、私のコードは今働いています!コード自体はいくつかの場所で壊れていて、Farzadと自分自身が修正を手助けしました。 JSON.parse()を含む行を削除すると、コードが完全に機能することがわかりました。 SQLセキュリティに関するご注意に関しては、私は十分に認識しており、ご指摘いただきありがとうございます。このコードは大学の割り当てプロジェクト向けであり、プロダクションコードとしてリリースされないため、これらのセキュリティ面をカバーすることはできません。しかし、私は将来のプロジェクトについてのあなたのコメントを書き留めました。私があなたに与えたフィードバックに感謝します! :) – MrPupper

+0

@MrPupper、 '' JSON.parse'が必要かどうか、 'dataType'が指定されているためjQueryライブラリが自動的にオブジェクトに変換するかどうかはわかりませんでした。そして、SQLiの脆弱性を知っていると思ったのですが、私はいつもそれを指摘しようとしています。だから、ユーザ/顧客を危険にさらす可能性のある脆弱なコードをリリースしない人がいます。あなたの研究に幸運。 – SpencerD

2

は、私はあなたがインデックス'postid'を逃したと思うし、このラインでこの

$postid = $_POST['editpostid']; 

を交換する必要があります。

$postid = $_POST['editpostid']['postid']; 

またはその代わりの送信

data: { 'editpostid': jsonObj }, 

この

を送信します
data: { 'editpostid': oldpostid }, 
+0

あなたの返信に感謝Farzad。私は今、私のコードが動作している、それはスペンサーとあなた自身の両方が見つけるのを助けた多くのエラーのためだった。私はあなたの2番目の提案が私のために働いていることがわかりました。そして、私はアレイ全体を廃止しました。私は助けに感謝します! :) – MrPupper

+0

@MrPupper助けてくれる以上に幸いです:) –

関連する問題