[英]AJAX Submit to PHP file not returning the data
When I try to submit data via AJAX to a PHP file, the submit works, and I can echo back a message from the PHP file. 当我尝试通过AJAX将数据提交到PHP文件时,提交工作正常,并且我可以从PHP文件中回显一条消息。 However, when I try to echo back the data I am submitting, or, echo back a message confirming that the data matches another variable in the PHP file(which it does), I still get a success message, but it says the data is not the same.
但是,当我尝试回显我提交的数据,或者回显一条消息确认该数据与PHP文件中的另一个变量匹配时(确实如此),我仍然收到一条成功消息,但它表示数据是不一样。
I am new to development and struggling a bit. 我是开发新手,有点挣扎。 Any help would be super.
任何帮助都将是超级。
The AJAX AJAX
$.ajax({
type: "POST",
url: "/check-cust.php",
data: "1234",
success: function(data) {
if (data == "") {
console.log("success, but no return");
} else {
alert(data); // show response from the php script.
}
},
error: function() {
alert("not working");
}
});
The PHP 的PHP
$temp_cust_id = "1234";
$data = $_POST['data'];
if ($data == $temp_cust_id) {
echo "it works";
} else {
echo "it doesnt work";
}
Is it maybe because I am submitting a JSON array, which is different to the string variable? 可能是因为我提交的JSON数组与字符串变量不同吗? That's just a guess though!
不过那只是一个猜测!
This false data: "1234",
, should be : 错误
data: "1234",
,应为:
data: {
data : 1234
}
Or give a better name : 或者给一个更好的名字:
data: {
myData : 1234
}
And in server side : 在服务器端:
$_POST['myData'];
Another way by using query string like so : 使用查询字符串的另一种方式是这样的:
data : 'myData=Hello',
// or data : 'firstParam=Hello&secondParam=Mate',
the way you are sending data is wrong, 您发送数据的方式是错误的,
data: {"data","1234"}
^ ^
name value
To put it all togeather, 总而言之,
$.ajax({
type: "POST",
url: "/check-cust.php",
data: {data:"1234"},// this the line in which you have error.
success: function(data) {
if (data == "") {
console.log("success, but no return");
} else {
alert(data); // show response from the php script.
}
},
error: function() {
alert("not working");
}
});
Then in php file, 然后在php文件中
$temp_cust_id = "1234";
$data = $_POST['data'];
if ($data == $temp_cust_id) {
echo "it works";// it will echo this for current output.
} else {
echo "it doesnt work";
}
post_data='1234';
$.ajax({
type: "POST",
url: "/check-cust.php",
data: "post_data="+post_data, //-------->>>Pass the data like this
success: function(data) {
if (data == "") {
console.log("success, but no return");
} else {
}
And in php file use: 并在php文件中使用:
$_POST['post_data'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.