[英]AJAX data not passing to PHP
I am having trouble passing AJAX data to PHP. 我无法将AJAX数据传递给PHP。 I am experienced with PHP but new to JavaScript.
我对PHP很有经验,但对JavaScript很新。
HTML / JavaScript HTML / JavaScript
<input type="text" id="commodity_code"><button id="button"> = </button>
<script id="source" language="javascript" type="text/javascript">
$('#button').click(function()
{
var commodity_code = $('#commodity_code').val();
$.ajax({
url: 'get_code.php',
data: "commodity_code: commodity_code",
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
});
</script>
PHP PHP
$commodity_code = $_POST['commodity_code'];
$result = mysql_query("SELECT description FROM oc_commodity_codes WHERE code = '$commodity_code'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I know the general AJAX fetch and PHP code is working as I can manually create the $commodity_code variable and the script works fine. 我知道一般的AJAX提取和PHP代码正在工作,因为我可以手动创建$ commodity_code变量,脚本工作正常。 I think my issue lies somewhere in passing the AJAX data to my PHP script.
我认为我的问题在于将AJAX数据传递给我的PHP脚本。
You forgot to add the method: 'POST'
in your AJAX Call. 你忘了在你的AJAX Call中添加
method: 'POST'
。 And you have some issues with your call. 你的电话有问题。 Check below:
检查如下:
$.ajax({
url: 'get_code.php',
method: "POST", // Change here.
data: {commodity_code: commodity_code}, // Change here.
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
Or to make it simple, use the shorthand function: 或者为了简单起见,使用速记功能:
$.post('get_code.php', {commodity_code: commodity_code}, function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
});
error in this line data: "commodity_code: commodity_code",
.. you can simple pass the commodity_code
variable.. 这行
data: "commodity_code: commodity_code",
错误data: "commodity_code: commodity_code",
..你可以简单地传递commodity_code
变量..
$.ajax({
url: 'get_code.php',
method: "POST",
data: commodity_code,
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.