2

I had a weird problem here. Please check the code below. I do not understand how this code below is created by somehow part of it is working, considering mixture of php variables and javascript variables.

First, let us see what the alert() outputs (take note that $lat and $lng is different from the array $vlat):

  1. In Line 8 of the code below, alert(eventlocation) properly displays the coordinates of the GoogleMap latlng (so the implementation is correct)

  2. In Line 13, alert(s) was able to display incrementing values (i.e. 0,1,2,3,4,..) based on the for loop in the previous line so it is also correct.

  3. In Line 14, alert($vlat[0]) was able to display the latitude of the first element of that array (declared before this set of codes) so it is also correct

  4. In Line 15, alert($vlat[1]) was able to display the latitude of the second element of that array so it is also correct

  5. But in Line 16, alert($vlat[s]) displayed undefined.

Can anyone explain that? Thanks

    echo "<script src= 'http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA2jrOUq9ti9oUIF0sJ8it1RTNr3PHi_gURF0qglVLyOcNVSrAsRRu2C3WQApcfD0eh9NLdzf9My0b9w' type='text/javascript'> </script>
    <script language='javascript' type='text/javascript'>
    function getabc(){
        var eventlocation;
        var volunteerlocation;
        var s;
        eventlocation = new GLatLng($lat, $lng);
        //alert(eventlocation);
        var volunteerDist = new Array();
        s = $ctr;
        var tvid = new Array();
        for(s=0;s<$numrows;s++){
            //alert(s);
            //alert($vlat[0]);
            //alert($vlat[1]);
            //alert($vlat[s]);
        }
    }
    a = getabc();     < /script>";
Brandon Young
  • 523
  • 2
  • 8
  • 19

2 Answers2

1
alert($vlat[0]);
alert($vlat[1]);
alert($vlat[s]);

$vlat[0], $vlat[1] and $vlat[s] are parsed on the server before they is sent to the client. The first two can be resolved, but PHP does not know what s is, since s is only defined once the client side is reached.

Edit from chat discussion

$json = json_encode($vlat);

echo "<script language='javascript' type='text/javascript'>
   function test(){
       var obj = JSON.parse('$json');
       alert(obj);
   }
   < /script>";
user247702
  • 23,641
  • 15
  • 110
  • 157
0

The variable s that you are using to index the PHP array vlat is a variable that you declared in JavaScript. You cannot use it to index a PHP array.

What your code tries to do is to have PHP access a JavaScript variable, which it cannot. You can have PHP echo JavaScript, yes, but it doesn't work both ways.

Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37