Leaflet points from mysql database: .php 'json_encode' working but .js
'getJson' not
I have an issue that I have tried to solve for a couple of days now. Went
through all similar issues that I could find on the internet, and still no
result. On stackoverflow have also been posted similar questions, but none
seems to help or give me an alternative. I want to generate points in a
Leaflet map, from the data saved in a mysql (xampp) database called poi,
table called users. the db contains for test, only one record:
ID | name | lat | lng
1 | john | 45.654500 | 25.609037
representing the point ID, a description and a couple of coordinates
latitude/longitude
usin a PHP script called get_info.php, i get the data from the db and
encode it as JSON using the code:
<?php
$db = new PDO('mysql:host=localhost;dbname=poi', 'john', 'skilla');
$sql = "SELECT id, name, lat, lng FROM users;";
$rs = $db->query($sql);
if (!$rs) {
echo "SQL error\n";
exit;
}
$rows = array();
while($r = $rs->fetch(PDO::FETCH_ASSOC)) {
$rows[] = $r;
}
print json_encode($rows);
$db = NULL;
?>
when calling get_info.php separatelly from the browser, it returns the
following:
[{"id":"1","name":"john","lat":"45.654500","lng":"25.609037"}]
so, it is encodeing the database records to JSON format but when calling
it from a .js script, there is no result the script is called JSON.js:
$.getJSON("get_info.php", function(data) {
for (var i = 0; i < data.length; i++) {
var location = new L.LatLng(data[i].lat, data[i].lng);
var name = data[i].name;
var marker = new L.Marker(location);
marker.bindPopup("<div style='text-align: center; margin-left: auto;
margin-right: auto;'>"+ title +"</div>", {maxWidth:'200'});
users.addLayer(marker);
}
})
JSON.js is called in the index.html file as such:
<script src="src/JSON.js"></script>
also in index are other .js called in order to generate the map:
Leaflet map generated by properly interpreting the rest of the .js
all the other .js work properly. I have tried to test JSON.js by calling
it in another .html file. I am not sure that this is correct, but if it
is, it is still not giving any sign of the data being received:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$("#demo").live("click", function () {
$.getJSON("src/get_info.php", function(data) {
var name = data[i].name
if (data.length) {
$("#dv").html(name);
} else {
html = r.error.message
$("#dv").html(html);
}
}
)}
);
</script>
</head>
<body>
<form id="test">
<div id = "dv"></div>
<input type = "button" value = "GET" id = "demo" />
</form>
</body>
</html>
Can you please help me in solveing the problem and generateing points from
the database? Thank you
No comments:
Post a Comment