Trying to grab a json variable from a php file and pass to a javascript file. I'm making a leaflet map and I store the information for markers in a mysql database, I then use a php file to pull that information and put it into an array.
The problem: For some reason the Javascript file is not using the data correctly and I can't figure out why.
get-data.php
$db = new mysqli('localhost', 'testuser', 'testpassword', 'testdb');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$queryStmt = 'SELECT * FROM test';
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
if($result = $db->query($queryStmt)) {
while($row = mysqli_fetch_assoc($result)){
extract($row);
$markers = array(
'type' => 'Feature',
'properties' => array (
'name' => $name,
'type' => $type,
'id' => $id,
'country' => $country,
'territory' => $territory,
),
'geometry' => array(
'type' => 'Point',
'coordinates' => array($long,$lat)
)
);
array_push($geojson['features'], $markers);
}
};
header('Content-type: application/json');
echo json_encode($geojson, JSON_NUMERIC_CHECK);
$db = NULL;
data.js
var result = [];
$.get("get-data.php", function(geojson) {
result = geojson;
});
capitolsLayer = L.geoJson(result, {
//lots of stuff with maps and everything
index.php (where all the map code actually goes)
<script type="text/javascript" source="data.js"></script>
<script>
//lots of map code
var map = L.map();
capitolsLayer.addTo(map);
</script>
In the ajax call of data.js I tried adding
alert(result);
And what popped up was just [object Object]
On index.php no errors are shown the markers just simply don't appear.
EDIT Update with solution! After a lot of reading and learning and LOTS of digging I found the answer! I changed this:
$.get("get-data.php", function(data) {
result = data;
});
capitols = new L.geoJson(result, {
//map stuff here
To this:
$.getJSON("get-data.php", function(data) {
capitols.addData(data);
}).complete;
capitols = new L.geoJson(null, {
//map stuff here
[object Object]
is actually a good sign that you already have what you wanted... (js objects don't self-serialize like they would in a var_dump)result
lives (you can't "export" it out of the callback, so you need to bring the code to the data)