kinath_ru
kinath_ru

Reputation: 4678

PHP-AJAX-JSON Notice: Undefined index :

I'm trying to make a test page for sending google map cordinates to populate a mysql database. I'm using ajax to send data to php. Firebug shows that the data is sending. But this php error comes out. And the mysql database is populating without the map cordinates.

Here's the Ajax function:

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

This is the PHP page.

    <?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());
    }
?>

Then the following errors comes out.

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

Any help would be appreciated.Thanks.

Upvotes: 1

Views: 611

Answers (1)

newfurniturey
newfurniturey

Reputation: 38456

When you're POSTing the data as a query-string, try using the application/x-www-form-urlencoded Content-type, not the application/json one that you currently are:

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

Upvotes: 2

Related Questions