简体   繁体   中英

Passing PHP Array to Javascript with Json_encode

I am trying to pass a php array to a javascript variable as an object to use in google maps on the same page/file. I am not able to send out an alert when testing the array in javascript.

PHP

while( $row = $query->fetch_assoc() ){
$street_address = $row['street_address'];
$zip = $row['zip'];
$state = $row['state'];
$lat = $row['lat'];
$lng = $row['lng'];
$test = $row['sellerDB_test'];

$firstName = $row['first_name'];
$lastName = $row['last_name'];
$email = $row['email'];
$phone = $row['phone'];

/* Each row is added as a new array */
$locations = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);

JS

var map;
        var Markers = {};
        var infowindow;
        var locations = '<?php echo json_encode($locations); ?>';
        var location = JSON.parse(loactions);
        alert(locations[0]);

I am getting this error

Uncaught ReferenceError: loactions is not defined at account:299

@Ghost is right. I did not notice that the $locations is inside while loop. So You should define $locations = []; before while loop. And then keep adding multiple records from while loop. So the updated code should be like:

$locations = [];
while( $row = $query->fetch_assoc() ){
    $street_address = $row['street_address'];
    $zip = $row['zip'];
    $state = $row['state'];
    $lat = $row['lat'];
    $lng = $row['lng'];
    $test = $row['sellerDB_test'];

    $firstName = $row['first_name'];
    $lastName = $row['last_name'];
    $email = $row['email'];
    $phone = $row['phone'];

    /* Each row is added as a new array [] */ 
    $locations[] = array( 'streetAddress'=>$street_address, 'state'=>$state, 'zip'=>$zip, 'lat'=>$lat, 'lng'=>$lng, 'test'=>$test, 'first name'=>$firstName, 'last name'=>$lastName, 'email'=>$email, 'phone'=>$phone);
}

And after this, you should put the JS code snippet.

And use it like this:

JS cpde:

var map;
var Markers = {};
var infowindow;
var locations = <?php echo json_encode($locations); ?>;
var location = JSON.parse(loactions);
alert(location.streetAddress);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM