I need to send a json array from a php script to Javascript.
<?php
//controllo se sono presenti i parametri
if(isset($_GET['ID_utente']) && isset($_GET['Longitudine']) && isset($_GET['Latitudine']))
{
//Recupero il valore dei parametri
$ID_utente = $_GET['ID_utente'];
$Longitudine = $_GET['Longitudine'];
$Latitudine = $_GET['Latitudine'];
}
//eseguo la connessione al database sul server locale
//inserendo nome utente e password
$conn = mysql_connect('localhost', 'realegr', 'rabredugbo19');
//gestione degli errori
// if (!$conn) {die('Impossibile connettersi: ' . mysql_error());}
//seleziono il databse
mysql_select_db("my_realegr") or die( "Impossibile selezionare il database.");
//creo una stringa sql di inserimento con i valori
//recuperati dall'url
$sql = "INSERT INTO `my_realegr`.`DatiSinistro`
(
`ID_sinistro` ,
`Tempo_Server` ,
`Tempo_Locale` ,
`ID_utente`,
`Longitudine`,
`Latitudine`
)
VALUES
(
NULL , CURRENT_TIMESTAMP , NULL , '" . $ID_utente . "', '" . $Longitudine . "', '" . $Latitudine . "')
";
$q = "SELECT Longitudine, Latitudine FROM DatiSinistro ORDER by ID_sinistro
DESC LIMIT 1";
$result = mysql_query($q, $conn);
if($row = mysql_fetch_assoc($result)) {
echo json_encode([
'status' => true,
'latitude' => $row['Latitudine'],
'longitude' => $row['Longitudine'],
]);
}
//gestione degli errori
if(! $result ){die('Impossibile eseguire la query: ' . mysql_error());}
//chiudo la connessione al db
mysql_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBkEtPH07_xBVh8dWBzCQYtWimkOUnPGMQ&callback=initMap"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap(){
var $request = $.get('http://realegr.altervista.org/ProvaReale1.php');
$request.done( function(data) {
alert(data);
var pasedData = JSON.parse(data);
alert(pasedData.latitude);
var uluru = {lat: pasedData.latitude, lng:pasedData.longitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
})
}
</script>
</body>
</html>
When I load Maps,alert(data) shows me : {"status":true,"latitude":"45.062583","longitude":"7.662160"}
So PHP script seems work well and besides Javascript receives JSON array With "var pasedData = JSON.parse(data); " do I obtain an array parsed?? When I try to show the content with alert(pasedData[0]) it shows me "undefined".What's wrong?
</div>