2012-10-23 177 views
1

我正在试图制作一个测试页面来发送Google地图坐标以填充mysql数据库。我使用ajax发送数据到php。 Firebug显示数据正在发送。但这个PHP错误出来了。而且mysql数据库在没有地图坐标的情况下填充。PHP-AJAX-JSON注意:未定义索引:

这里是Ajax的功能:

function sendData(geodata){ 
    var hr = new XMLHttpRequest(); 
    hr.open("POST","getdata.php",true); 
    hr.setRequestHeader("Content-type","application/json"); 

    if(hr.readyState==4 && hr.status==200){ 
      var data = JSON.parse(hr.responseText); 
      alert("Data received about "+data); 
      }//end if 

    hr.send("geodata="+geodata); 
}//close sendData 

这是PHP页面。

<?php 
header("Content-Type : application/json"); 

$loc = $_POST["geodata"]; 

$username="root"; 
$password=""; 
$database="location"; 

$connection = mysql_connect('localhost',$username,$password); 
if(!$connection){ 
    die('Unable to connect to the server '.mysql_error()); 
    } 

$selectdb = mysql_select_db($database); 
if(!$selectdb){ 
    die('Unable to connect to database'.mysql_error()); 
    } 

$query = "INSERT INTO `location_data`(`ltlng`) VALUES ('".$loc."')"; 
$result = mysql_query($query); 
if(!$result){ 
    die('Invalid query : '.mysql_error()); 
    } 
?> 

然后出现以下错误。

(!) Notice: Undefined index: geodata in C:\wamp\www\IndustryProject\SampleDataGen\getdata.php on line 4 

任何帮助将不胜感激。谢谢。

+0

降低你的错误报告级别,未定义的索引引用生成注意事项。 –

+1

我们没有看到你在哪里设置传递给你的函数sendData()的变量'geodata'。发布更多的JavaScript,其中该功能实际上被称为... –

回答

2

当您发布的数据作为查询字符串,请尝试使用application/x-www-form-urlencoded内容类型,而不是application/json一个你目前是:

hr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
+0

这就像一个魅力....感谢newfurniturey .....它工作.... :-) –