0

Okay. So i've been here all day, reading and following all the solutions about this topic but i got nothing. Nothing works. Can you show me how to do it, with complete and understandable example. Im new to JavaScript and PHP, so how can i get array values from a PHP file to JavaScript. I tried doing this: var locations = <?php echo json_encode($location); ?>; but i gives me error. and no one answered why. This code here:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
  ['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
  ['Camarillo Household', 6.4345278, 125.58975, 2],
  ['Perez Household', 6.4343889, 125.59202777777777, 3],
  ['Usman Household', 6.4338056, 125.59191666666666, 4],
  ['Lim Household', 6.4333889, 125.59419444444444, 5]
];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(6.40, 125.60),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

i want to change the value of variable locations from the value from my database. so i got this PHP file:

<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

 $sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
 $result = mysqli_query($conn, $sql);
  
 if(mysqli_num_rows($result) > 0){
  // output data of each row
  
  for($i=0;$i<mysqli_num_rows ( $result );$i++){
   $row=mysqli_fetch_row($result);

   $location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
   //echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
  }
  
 }else{echo "0 results";}
?>

it works fine. it outputs the data from the database. now what i want to know is how can i convert that value from the database to a value i can use in place of the locations variable so that the markers will appear on the map? var locations = <?php echo json_encode($location); ?>; this guy give me error, i followed every instruction i can, but still it's error. can u modify my code so that it works or can u just point me out in the WORKING/FUNCTIONAL code there is to your knowledge. Please, help me. I'm in deep trouble here.

New to Programming
  • 133
  • 1
  • 3
  • 13
  • 2
    Possible duplicate of http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript – inverted_index Feb 08 '16 at 08:41
  • What error you are getting? – AnkiiG Feb 08 '16 at 08:41
  • You're not generating your `$location` array in PHP the correct way. You're creating an array of array(1)'s each containing a single string. When using `json_encode` on that you're not getting what you're expecting. Use `$location[] = array($row[0], $row[1], $row[2], $i+1);`. – ccKep Feb 08 '16 at 08:43
  • `Uncaught SyntaxError: Unexpected token <` when i try to replace the value of `locations` to this `var locations = ;`, the examples i read showed like this and said it's fine. but when i tried it won't work. what did i do wrong? – New to Programming Feb 08 '16 at 08:44
  • still same error, sir. the error message said it's in `var locations = ;`, i coded it correct, right? the error is: `Uncaught SyntaxError: Unexpected token <` – New to Programming Feb 08 '16 at 08:50

2 Answers2

2

Try to change location[] variable from :

$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));

to

$location[]= array($row[0],$row[1],$row[2],($i+1));

I have added full code below and its working :

<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
$result = mysqli_query($conn, $sql);

if(mysqli_num_rows($result) > 0){
    // output data of each row

    for($i=0;$i<mysqli_num_rows ( $result );$i++){
        $row=mysqli_fetch_row($result);

        $location[]= array($row[0],$row[1],$row[2],($i+1));
        //echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
    }
}else{echo "0 results";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
    type="text/javascript"></script>
</head>
<body>
    <div id="map" style="width: 500px; height: 400px;"></div>

    <script type="text/javascript">
    /*var locations = [
  ['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
  ['Camarillo Household', 6.4345278, 125.58975, 2],
  ['Perez Household', 6.4343889, 125.59202777777777, 3],
  ['Usman Household', 6.4338056, 125.59191666666666, 4],
  ['Lim Household', 6.4333889, 125.59419444444444, 5]
];*/
var locations = <?php echo json_encode($location); ?>;


    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(6.40, 125.60),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>
AnkiiG
  • 3,468
  • 1
  • 17
  • 28
  • i tried it, sir.. but still same error. it doesn't even show a map. the error message points me to `var locations = ;` .i followed from other suggestions. i coded it correctly, right? – New to Programming Feb 08 '16 at 08:58
  • @NewtoProgramming Please check full code I added above. – AnkiiG Feb 08 '16 at 08:59
  • i tried the code above, sir. but i just loads a blank page with this text: `0){ // output data of each row for($i=0;$i"; } }else{echo "0 results"; } ?>` – New to Programming Feb 08 '16 at 09:06
  • Have you added full code in a `.php` file? @NewtoProgramming – AnkiiG Feb 08 '16 at 09:08
  • it says: `Connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.` with two warnings `Warning: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\wamp\www\NewBie.php on line 8` and `Warning: mysqli_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\wamp\www\NewBie.php on line 8` .. – New to Programming Feb 08 '16 at 09:18
  • @NewtoProgramming : Are the variable values correct `$servername = "host"; $username = "username"; $password = "password"; $dbname = "dbname";` ? Have you changed the dummy values to original one? – AnkiiG Feb 08 '16 at 09:20
  • i changed them before i saved but, >_< i got it working now. it's just that i save it in `.html` file, so the `json_encode()` might not worked because of that. thank you very much, sir. you were a great help. im sorry if i used much of your time, im really new to javascript and php so i find it hard to understand. thank you so much. :) – New to Programming Feb 08 '16 at 09:25
  • it's from your suggestions and code, sir. thank you so much. i really thank you for this. :) – New to Programming Feb 08 '16 at 09:28
0

Your array is not "realy" an array if your code is :

$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));

I think the result will be somthing like this :

<script type="text/javascript">
    var locations = [["Municipal Hall, 6.414333734068895, 25.61093270778656, 1"],["Camarillo Household', 6.4345278, 125.58975, 2"],......];

.....
</script>

try with :

$location[]= array($row[0],$row[1],$row[2],($i+1));

Edit: I don't recommend to use this mean to pass PHP array to JS beacause it overload the html page and navigator can't cahe the content of your array. the beter way to do this is to use Ajax function at the page loading with this http://api.jquery.com/jquery.ajax/

C.Rouillon
  • 588
  • 1
  • 4
  • 11
  • i tried your suggestion. but still it doesn't load. `var locations = ;` is produces error, cause the console message pointed it out. i coded it correctly, right? or is there something i missed? – New to Programming Feb 08 '16 at 08:56
  • Could you post the content of the JS location var with console.debug(locations) ? – C.Rouillon Feb 08 '16 at 09:12