2014-03-06 24 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']; 

希望它有帮助。