-1

I'm having problems with the following loop, which generates null results for the variable newLat[i]. However, when I directly populate newLat[0] (in the last 2 lines) it works fine. Any thoughts?

PHP:

$sql = "SELECT `id`, `name`, `lat`, `lng` FROM `markers` " ;
$result = $dbc->query($sql);
$hits = $result->num_rows ;
echo "<br /> Records = " ;
echo "$hits <br />";
while($row = $result->fetch_assoc()) {
    $MarkerID[] = $row['id'];
    $MarkerName[] = $row['name'];
    $MarkerLat[] = $row['lat'];
    $MarkerLng[] = $row['lng'];
}       

and Javascript:

var myhits = <?php echo json_encode($hits); ?>;
var newLat = new Array (myhits);    

for (var i = 0; i < myhits; i++) {
    newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
    document.write (newLat[i]);
}

newLat[0] = <?php echo json_encode($MarkerLat[0]); ?>;
document.write (newLat[0]);

2 Answers2

0
for (var i = 0; i < myhits; i++) {
    newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
    document.write (newLat[i]);
}

You're trying to include PHP code in your JavaScript loop. This is simply impossible, as all PHP is evaluated on the server, while JS is on the client. Open your webpage and "view source" -- you'll see there probably isn't anything on that line.

You'll have to figure out another way to do this; perhaps send $MarkerLat to the client the same way you do hits.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

You can't use a FOR pointer inside a different language block:

for (var i = 0; i < myhits; i++) {
    newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
    document.write (newLat[i]);
}

You are trying to use a JavaScript i inside a PHP block. Not only has the PHP block executed by this point, it wouldn't know what to do with that i. It will be 0.

You need to dump the contents of $MarkerLat[i] into a JavaScript array before running it through your loop.

durbnpoisn
  • 4,666
  • 2
  • 16
  • 30