2017-10-08 52 views
0

我試圖將一個JavaScript變量傳遞給PHP,以便可以創建(MySQL)查詢以返回單個記錄。用戶將輸入一個搜索字符串,然後返回許多記錄包含匹配的字符串。然後用戶將選擇他們想要查看的單個記錄。如何使用onclick事件將Javascript變量傳遞到PHP

這裏是我的HTML(recipe_summary.php):

<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
    <script type="text/javascript" src="script.js"></script>  
</head> 
<body> 
<table> 
    <tr> 
     <th>Recipe ID</th> 
     <th>Title</th> 
     <th>Ingredients</th> 
     <th>Recipe</th> 
    </tr> 
    <?php foreach($search_results as $result) { ?> 
    <tr> 
     <td><a href="#" name="<?php echo $result['recipe_id']; ?>"><?php echo $result['recipe_id']; ?></a></td> 
     <td><?php echo $result['title']; ?></td> 
     <td><?php echo $result['ingredients']; ?></td> 
     <td><?php echo $result['recipe']; ?></td> 
    </tr> 
    <?php }; ?> 
</table> 
</body> 

這裏是我的JS(的script.js):

$(document).ready(function() { 
     var myText; 

     $("a").click(function(){ 
      myText = $(this).text(); 
      ajax_post(myText); 
     }); 

     function ajax_post(myText){ 
      var hr = new XMLHttpRequest(); 
      var url = "recipe_result.php"; 
      var passedVal = myText; 
      var myVal = "recipe_id=" + myText; 

      hr.open("POST", url, true); 
      hr.setRequestHeader("Content_type","application/x-www-form-urlencoded"); 
      hr.onreadystatechange = function() { 
       if(hr.readyState == 4 && hr.status == 200) { 
        var return_data = hr.responseText; 
        document.getElementById("status").innerHTML = return_data; 
       } 
      } 
      hr.send(myVal); 
     };  
}); 

這裏是recipe_result.php:

<!doctype html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>Untitled Document</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
    <script type="text/javascript" src="script.js"></script> 
</head> 
<body> 
    <?php 
     if(isset($_POST['recipe_id'])){ 
      echo "SET"; 
     } else { 
      echo "NOT SET"; 
     } 

    ?> 
    <div id="status"></div> 

</body> 
</html> 

用戶將點擊一個錨標籤(recipe_summary.php),這將觸發script.js上的點擊事件,該事件將存儲recipe_ID(和th是我迷路的地方)並將它傳遞給ajax_post()。從這裏我試圖將存儲的變量作爲php變量發送到'recipe_result.php',然後我將在MySQL中使用該變量僅返回選定的記錄。

關於recipe_result.php $ _POST ['recipe_id']沒有被設置,所以我不知道我的錯誤在哪裏。

我不熟悉ajax,但從我讀過的ajax看來是解決方案。我看過很多教程(ajax_post()中的所有內容都來自我試圖遵循的教程),但通常他們從HTML表單開始,然後將結果寫入同一頁面。

+0

是什麼'recipe_result.php'的內容? – Farnabaz

+0

目前沒有;我不確定寫什麼。 – RunzWitScissors

+0

我不明白是什麼問題。你有一些代碼。它看起來應該做你所問的。你沒有說過當你運行它時會發生什麼。您尚未從開發人員工具控制檯引用任何錯誤消息。您尚未描述在開發人員工具的網絡選項卡中可見的請求和響應中的任何問題。所以......你在問什麼? – Quentin

回答

0

你的代碼看起來不錯,剛讀recipe_id在PHP這樣

echo $_POST['recipe_id']; 

還看$_POST可變documentation

+0

用recipe_result.php更新原始文章... – RunzWitScissors

相關問題