2016-12-15 6 views
-1

Javascript変数をPHPに渡したいが、決して設定されていない。私は1つの.phpファイル内のすべてを持っているJavascript変数をPHPに渡す

CODE:私は、変数を渡すためにはXMLHttpRequestを使用しています

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <link rel="stylesheet" type="text/css" href="asd.css"> 
    <title>Tabulka</title> 
</head> 
<body> 

<script> 
$(document).ready(function(){ 
    $("#table tr").click(function(){ 
     $(this).addClass('selected').siblings().removeClass('selected'); 

     var value = $("#table tr.selected td:first").html(); 

     var xmlhttp = new XMLHttpRequest(); 
     xmlhttp.open("GET", "tabulka.php?id=" + value, true); 
     xmlhttp.send(); 
    }); 
}); 
</script> 
<table id="table"> 
    <tr> 
     <th>A</th> <th>A</th> <th>B</th> <th>C</th> <th>D</th> 
    </tr> 

    <tr> 
     <td>51</td> <td>41</td> <td>1515</td> <td>419</td> <td>asd</td> 
    </tr> 

    <tr> 
     <td>52</td> <td>41</td> <td>1515</td> <td>419</td> <td>asd</td> 
    </tr> 

    <tr> 
     <td>63</td> <td>41</td> <td>1515</td> <td>419</td> <td>asd</td> 
    </tr> 
</table> 

<form method="POST"> 
    <input type="submit" name="ok-submit" class="ok" value="OKOK"> 
</form> 
</body> 
</html> 


<?php 
if(isset($_REQUEST['id'])){ 
    echo $_REQUEST['id']; 
} 
?> 

。テーブル行をクリックした場合のように動作します。最初のtdはPHP変数に渡され、それをプリントアウトします。しかし彼は$ _REQUEST ['id']は設定されません。

+0

いいえ、それは動作しません。 – Phiter

+0

ajaxレスポンスを返すファイルは、リクエストを行っているファイルとは別のファイルでなければなりません。そうでないと条件を使うことができますが、それは醜いでしょう。 – Phiter

+3

[JavaScript変数をPHPに渡す方法]の複製がありますか?(http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) –

答えて

0

PHPによって処理サーバ側であることを別のページにはJavaScriptを介してデータを渡す結果を構築し、次いで、ジャバスクリプトが存在する現在のページ上に表示することができます。それはかなり滑らかで、ページリフレッシュやフォームを提出する必要はありません。

私の例は簡単な検索機能です。ユーザーはクエリ文字列を入力して検索を実行します。テキストボックスの内容はjavascript関数に渡され、データベースクエリを実行するPHPページに渡されます(または必要なものは何でも)。HTMLをいくつか作成し、ユーザーが現在のページにそのHTMLを出力します。ここで

<div id='studentResults'></div> 

はHTMLです::

<div id='quickStudentLookup'> 
     <div> 
      <p>Quick Search</p> 
     </div> 

     <div> 
      <input id='queryString' name='queryString' type='text' placeholder='First OR Last Name' /> 
      <input type='submit' value='Search' onclick="javascript:ajax_post();" /> 

     <div id='studentResults'></div> 
     </div> 
    </div> 

Javascriptを:

function ajax_post(){ 
     // Create our XMLHttpRequest object 
     var hr = new XMLHttpRequest(); 

     var url = "studentSearch.php"; // this is a file that would take the queryString, perform something on it and echo some HTML back. The HTML will end up as innerHTML of the div id studentResults 

     // Create some variables we need to send to our PHP file 
     var queryString = document.getElementById("queryString").value; 
     var vars = "queryString="+queryString; 
     hr.open("POST", url, true); 

     // Set content type header information for sending url encoded variables in the request 
     hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     // Access the onreadystatechange event for the XMLHttpRequest object 
     hr.onreadystatechange = function() { 

      if(hr.readyState == 4 && hr.status == 200) { 
       var return_data = hr.responseText; 
       document.getElementById("studentResults").innerHTML = return_data; 
      } 
      else{ 

      } 
     } 
     // Send the data to PHP now... and wait for response to update the status div 
     hr.send(vars); // Actually execute the request 
} 

PHP: これはあなたが望むものは何でもすることができ、この内のinnerHTMLのはDIVとしてこの場合には、それをダンプします。ここでは、データを取得し、データベースに照会し、結果をエコーする簡単な例を示します。エコーはIDがstudentResultsのDIV内で発生します。これは上記のJSで定義されています。

<?php 
     // database connection omitted 
     $queryString = $_POST['queryString']; // get var from post 

     $studentSearch = "SELECT 
     student.student_id, 
     student.firstName, 
     student.lastName, 
     student.studentID 
     FROM 
     student 
     WHERE student.lastName = :queryString 
     LIMIT 10"; // build query 

     $sth = $handler->prepare($studentSearch); // pdo to run query 
     $sth->execute(array(':queryString'=>$queryString)); 
     $results = $sth->fetchAll();     

     foreach($results as $r){ // loop through results and output 
      $firstName  = $r['firstName']; 
      $lastName   = $r['lastName']; 
      $studentID  = $r['studentID']; 

      echo "<p>$firstName $lastName - $studentID</p>"; 

     } 

?> 

希望すると助かります!

0

現在のページのJavaScriptから現在のページに変数値を渡すことはできませんPHPコード... PHPコードはサーバー上で実行され、クライアント側で何が起こっているのかは分かりません。

GETメソッドまたはPOSTメソッドでフォームを送信するなど、別のメカニズムを使用して、htmlフォームからPHPコードに変数を渡す必要があります。

<DOCTYPE html> 
<html> 
    <head> 
    <title>My Test Form</title> 
    </head> 

    <body> 
    <form method="POST"> 
     <p>Please, choose the salary id to proceed result:</p> 
     <p> 
     <label for="salarieids">SalarieID:</label> 
     <?php 
      $query = "SELECT * FROM salarie"; 
      $result = mysql_query($query); 
      if ($result) : 
     ?> 
     <select id="salarieids" name="salarieid"> 
      <?php 
      while ($row = mysql_fetch_assoc($result)) { 
       echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one) 
      } 
      ?> 
     </select> 
     <?php endif ?> 
     </p> 
     <p> 
     <input type="submit" value="Sumbit my choice"/> 
     </p> 
    </form> 

    <?php if isset($_POST['salaried']) : ?> 
     <?php 
     $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid']; 
     $result = mysql_query($query); 
     if ($result) : 
     ?> 
     <table> 
      <?php 
      while ($row = mysql_fetch_assoc($result)) { 
       echo '<tr>'; 
       echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others 
       echo '</tr>'; 
      } 
      ?> 
     </table> 
     <?php endif?> 
    <?php endif ?> 
    </body> 
</html> 
+0

ありがとうございました。 –

関連する問題