I want to send geographic data (latitude & longitude) to a mySQL database with Ajax call and PHP script. Both Ajax and PHP scripts look ok for me but nothing goes to the database. I've try different syntax and option (like PDO with array) to manage MySQL but still nothing... Do you have an idea of what is going wrong ?
Thank you very much for your help, Flo.
The Jquery code of my Html page is simple :
function getCoordPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajaxSetup({
url: "insert-in-bdd.php",
type: "POST",
});
$.ajax({
data: 'latitude='+latitude+'&longitude='+longitude,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
});
}
}
The first PHP script I try (insert-in-bdd.php) is:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['latitude']) && isset($_POST['longitude'])){
$latitude = ($_POST['latitude']);
$longitude = ($_POST['longitude']);
$db = mysql_connect(localhost, root, "");
$select = mysql_select_db(madb, $db);
mysql_query('INSERT INTO location (lat,lng)
VALUES (:longitude, :longitude)');
}}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
The second PHP script I try (with PDO and array), same name : insert-in-bdd.php is:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['latitude']) && isset($_POST['longitude'])){
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=madb', 'root', '');
$req = $bdd->prepare('INSERT INTO location(lat, lng) VALUES(:lat, :lng)');
//$req = $bdd->prepare('UPDATE location SET lat = :lat');
$req->execute(array(
'lat' => $_POST['latitude'],
'lng' => $_POST['longitude']
));
}}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
?>
var_dump($_POST)in PHP?mysql_query()doesn't accept input parameters like:latitude.:as in:lat,:lngrather thanlat, lnginside theexecute()call.