php - Variables in javascript while keeps resetting -


this question has answer here:

i have while loop in code:

while (i < 5) { var pos = new google.maps.latlng(<?php echo json_encode($lat[$b]); ?>,<?php echo json_encode($lon[$b]);?>); var marker = new markerwithlabel({     position: pos,     draggable: true,     raiseondrag: true,     map: map,     icon: 'icon.png',     labelcontent: <?php echo json_encode($unidad[$b]); $b=$b+1;?>,     labelanchor: new google.maps.point(22, 0),     labelclass: "labels", // css class label     labelstyle: {opacity: 0.75},     });     google.maps.event.addlistener(marker, "click", function (e) { iw1.open(map, this); });     i++; } 

now, let me explain code , happening. first of using javascript , php because need info db, , add map (google maps) need use javascript.

on first round value of $b pass 0 1, going through first loop value resets 0 again. it's not $b takes 0 default, because if declare $b=6 before while loop values of $b 6 , 7.

what doing wrong? or how should doing this? appreciated. please excuse me mistakes since english not first language.

this new code, pass array php javascript (i didn't know easy) here new code:

var lat = <?php echo json_encode($lat)?>; var lon = <?php echo json_encode($lon)?>; var unidad = <?php echo json_encode($unidad)?>;  while (i < <?php echo json_encode($a)?>)  {  var pos = new google.maps.latlng(lat[i],lon[i]);     var marker = new markerwithlabel({        position: pos,        draggable: true,        raiseondrag: true,        map: map,        icon: 'icon.png',        labelcontent: unidad[i],        labelanchor: new google.maps.point(22, 0),        labelclass: "labels", // css class label        labelstyle: {opacity: 0.75},        }); 

you hardcoding $lat[$b] values php javascript literals. resulting in this:

new google.maps.latlng("lat of b", 

you should encode php variables javascript variables instead of literals:

var lat = <?php echo json_encode($lat); ?>; var b = <?php echo json_encode($b); ?>; while(i<5) {  ... actual code 

that way php creating javascript variable instead of literal.

keep in mind page goes trough 2 stages.

  1. server side rendering php code gets evaluated.
  2. client side code javascript evaluated.

you need create javascript variable $lat well.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -