每次使用$_POST方法时未定义变量$id



我使用post方法来获取id,但每次都告诉我未定义变量$id这里是我的代码:

<?php    
require 'DBConnection.php';
$code='';
if(isset($_POST["ID"])){
if($_POST(["ID"]) != ''){
$id = $_POST['ID'];
$get_c = $pdo->prepare("SELECT * FROM all_menu WHERE `ID` = '".$id."'");
$get_c->execute(); 
while ($row = $get_c->fetch()) {
$code .= $row['item_code'];
}
echo $code;
}
}

编辑:我使用这段代码从下拉选项中进行选择,以获得下拉列表中值的ID例如,我的下拉菜单中有三个选项第一个是"百事可乐"当我选择"百事"我需要把它的ID输入我使用PHP和Ajax在这段代码。

这是我的Ajax代码:

<script>
$(document).ready(function(){
$('#itemname').change(function(){
var code = $(this).val();  
$.ajax({
type: 'POST',
url: 'pages/GetCode.php',
data:{code:code},
success: function(data){
document.getElementById("itemcode").value = data;
},
error: function (jqXHR, textStatus, errorThrown){ 
alert(errorThrown);
}
});
});
});
</script>

如果你是从javascript AJAX调用这个php页面,那么我可以看到唯一的参数是"code",那么你怎么能期望"ID"在邮报?

要么修改javascript文件,要么修改PHP文件

下面的javascript将发送"code"作为POST参数,data:{"code":code}

<script>
$(document).ready(function(){
$('#itemname').change(function(){
var code = $(this).val();  
$.ajax({
type: 'POST',
url: 'pages/GetCode.php',
data:{"code":code},
success: function(data){
document.getElementById("itemcode").value = data;
},
error: function (jqXHR, textStatus, errorThrown){ 
alert(errorThrown);
}
});
});
});
</script>

使用"code"而不是"ID"作为PHP的POST参数

<?php    
require 'DBConnection.php';
$code='';
if(isset($_POST["code"])){
if($_POST(["code"]) != ''){
$id = $_POST['code'];

旁注:不要在SQL查询中使用用户输入(这里的"code"),否则您的SQL查询将向注入打开。

您正在发送参数code作为ajax数据,您正在获取参数id改变$_POST['id']to$_POST['code']

$id = $_POST['code'];

最新更新