[英]Ajax Post Value not being passed to php file
我在將變量傳遞到php頁面時遇到問題。
這是下面的代碼:
var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string
$.ajax({
type: "POST",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
PHP:
$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here
$con=mysqli_connect("localhost","root","pass","mydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");
mysqli_close($con);
}
我想念什么嗎? 實際數據正在保存到數據庫中,但$ first和$ second值未傳遞到php文件。
您正在使用POST類型,請在POST中進行檢索:
$first = $_POST['first'];
$second = $_POST['second'];
或更改您的JQuery調用:
$.ajax({
type: "GET",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
因為您正在傳遞數據引發POST
方法並嘗試使用GET
所以請更改這兩行
$first = $_POST['first']; //This is not being passed here
$second = $_POST['second']; //This is not being passed here
或者只是將您的方法更改為jQuery中的GET
type: "GET"
您正在ajax中使用類型:“ POST”,並嘗試使用$ _GET獲取,請嘗試
$first = $_REQUEST['first']; //This is not being passed here
$second = $_REQUEST['second'];
並且有一種方法可以像這樣傳遞數據
$.ajax({
type: "POST",
url: "test.php",
data: {first: varFirst,second: varSecond},
success: function(){
alert('seccesss');
}
});
在那里你可以使用
$_POST['first'];
$_POST['second'];
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.