2014-03-06 52 views
0

我在將該變量傳遞給php頁面時遇到問題。未將Ajax Post值傳遞給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); 


} 

我我失去了一些東西?實際的數據保存到數據庫BUT $ first和$ second value沒有被傳遞給php文件。

+0

您應該將您的數據作爲JSON傳遞。 – Chris

回答

2

您正在使用POST類型,在POST檢索:

$first = $_POST['first']; 
$second = $_POST['second']; 

或更改您的JQuery電話:

$.ajax({ 
    type: "GET", 
    url: "test.php", 
    data: "first="+ varFirst +"&second="+ varSecond, 
     success: function(){ 
      alert('seccesss'); 
    } 
}); 
2

這是appening因爲你正在傳遞數據擲POST方法,並嘗試用GET得到所以改變那兩條線

$first = $_POST['first']; //This is not being passed here 
$second = $_POST['second']; //This is not being passed here 

或者乾脆改變你的方法GET在你的jQuery

type: "GET" 
1

您正在使用類型:在阿賈克斯「POST」,並試圖使用$ _GET來獲取,嘗試

$first = $_REQUEST['first']; //This is not being passed here 
$second = $_REQUEST['second']; 
1

而且還有一個方法數據傳遞這樣的

$.ajax({ 
    type: "POST", 
    url: "test.php", 
    data: {first: varFirst,second: varSecond}, 
     success: function(){ 
      alert('seccesss'); 

    } 
}); 

而且有可以使用

$_POST['first']; 
$_POST['second']; 

希望它有幫助。