2

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
8
  • [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) Commented Jul 24, 2015 at 20:10
  • yeah I figured but I can't understand why the markers are not appearing on the map if the data was successfully brought over, looking at the php file and see what it outputs and it's in the correct format and everything. Commented Jul 24, 2015 at 20:11
  • cool, now all you need to do is move your marker populating code to the callback where result lives (you can't "export" it out of the callback, so you need to bring the code to the data) Commented Jul 24, 2015 at 20:13
  • I did not know that, sorry if this is a stupid question but couldn't I just add "return result" and "export" the json data out of the callback? I tired it and it doesn't work but I guess i'm just confused as to why you can't "export" the data. Commented Jul 24, 2015 at 20:20
  • well, you can push the data out of the callback, but the callback does one other thing that you need: it waits until the data is available until running the code. if you push it out, you still need to find a way to make the other data-needing parts wait. While you could do some kind of polling, that's ugly, slow, and rush risky. basically, you need to just bite the bullet of async JS and refactor away from a top-down flow. there's no easy workaround, save some generator abuse in ES6... Commented Jul 24, 2015 at 20:23

1 Answer 1

1

Try this way parsing the JSON data and accessing at json object..

var result = [];
$.get("get-data.php", function(geojson) {
    result = JSON.parse(geoJson);
    alert (result.properties.name);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.