How to access array data from PHP in JavaScript -
this question has answer here:
- how pass variables , data php javascript? 17 answers
i have code in php. works fine:
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "tsunami_simulation"; // 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 household a, location b a.household_id = b.household_id;'; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0){ for($i=0;$i<$num_rows;$i++){ $row=mysql_fetch_row($result); $location[]= $row[0].', '.$row[2].', '.$row[1].','.($i+1); //echo "household name: " . $row[0]. " - latitude: " . $row[1]. " - longitude " . $row[2]. " " .($i+1)."<br>"; } }else{echo "0 results";} ?>
now, want access array result php file in javascript. tried using json.parse(). doesn't work. used piece of code: var locations = '<?php echo json_encode($location); ?>';
not give errors. followed locations = json.parse(locations)
, returns <?php echo json_encode($location); ?>
, not data. how can proper data, methods long works, please me. btw, want array database in wamp , put markers on googlemap using coordinates array. me please!..
edit: there's other code have access data:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>new 1 -- google maps multiple markers</title> <script src="http://maps.google.com/maps/api/js?v3" type="text/javascript"></script> </head> <body> <div id="map" style="width: 500px; height: 400px;"></div> <?php include 'location.php';?> <script type="text/javascript"> var locations = <?php echo json_encode($location, json_hex_tag); ?>; 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; (i = 0; < locations.length; i++) { loc_array = locations[i].split(","); marker = new google.maps.marker({ position: new google.maps.latlng(loc_array[1], loc_array[2]), map: map }); google.maps.event.addlistener(marker, 'click', (function(marker, i) { return function() { infowindow.setcontent(loc_array[0]); infowindow.open(map, marker); } })(marker, i)); } </script> </body> </html>
$location[]= array($row[0], $row[2], $row[1], $i+1);
and then
var locations = <?php echo json_encode($location, json_hex_tag); ?>
note: no json.parse
needed, no quotes, , not manual concatenation of variables form quasi-array.
edit: json_hex_tag
highly recommended, if have php 5.3.3+, plain json_encode
not quite secure.
Comments
Post a Comment