0

I am trying to loop through my SQL result with PHP and JavaScript to set markers on a LeafLet Map. The Data contains the name, latitude, longitude and number.

Here is my code:

var ticker = <?php echo mysqli_num_rows($result); ?>;
for ( let i = 0; i < ticker; i++) {
  var latitude = <?php echo json_encode($row["latitude"]); ?>;
  var longitude = <?php echo json_encode($row["longitude"]); ?>;
  var marker = L.marker([latitude, longitude]).addTo(map);
  var popup = <?php echo json_encode($row["name"] . " " . $row["number"]); ?>;
  marker.bindPopup(popup);
}

It should add two markers, but somehow it only generates one marker with the data from the first entry.

Dharman
  • 30,962
  • 25
  • 85
  • 135
alb
  • 47
  • 7
  • 1
    It looks like it would create two markers on rhe same spot. You don't seem to be looping over $row. Instead of mixing php and js like this it would probably make a lot more sense to have php output the necessary data into a json array, pass that to JS, decode it and loop over that. – ADyson Feb 02 '23 at 07:56
  • i tried that, but i cant make it work. extracting the data from my json object always says its undefined – alb Feb 02 '23 at 09:34
  • var data = JSON.parse(JSON.stringify()); console.log(Object.values(data)); for ( let i = 0; i < data.length; i++) { console.log(data.Name); } – alb Feb 02 '23 at 09:40
  • 1
    Why would you call JSON.stringify on a value that already is JSON, only to then parse it again? You _just_ need to output the `json_encode` result - one of the main points of JSON is that it can be parsed as valid JavaScript code already, without needing any extra steps. https://stackoverflow.com/a/4885796/1427878 – CBroe Feb 02 '23 at 10:44
  • yip, thats true :D dunno what i thought there – alb Feb 02 '23 at 11:52

1 Answers1

1

Ok i found a solution. Thanks for any help!

PHP

$result = $conn->query($sql);
$values = [];
while($value = mysqli_fetch_array($result, MYSQLI_NUM)) {
    $values[] = $value;
}

JavaScript

var data = <?php echo json_encode($values); ?>;

for ( let i = 0; i < data.length; i++) {
    var name = data[i][0];
    var lat = data[i][1];
    var lon = data[i][2];
    var ums = data[i][3];
    var popup = name + ums;
    var marker = L.marker([lat, lon]).addTo(map);
    marker.bindPopup(popup);
}
ADyson
  • 57,178
  • 14
  • 51
  • 63
alb
  • 47
  • 7