0

So i'm making a google embedded page where i need some pinpoints declared. I want to store these in a database and get them the way you'd also fill a table with php.

My code should produce this:

['Street', coordinates, coordinates, ID],
['Street', coordinates, coordinates, ID],
['Street', coordinates, coordinates, ID],
['Street', coordinates, coordinates, ID]
etc.

Right now i got this:

<script type="text/javascript">
    var locations = [
        <?php while ($row2 = mysqli_fetch_array($result2)) {
        echo '[' . $row2['Straat'] . ',' . $row2['Noorderbreedte'] . ',' . $row2['Westerlengte'] . ',' . $row2['ID'] . '],';
    }
        ?>

Can't workout how this should work or if there is an easier way to just get database objects via JS.

3
  • 1
    use json_encode() to transform php array to JS array Commented Apr 20, 2016 at 10:02
  • why don't you make a XHR request to get that that on page load instead of writing the object in HTML? Commented Apr 20, 2016 at 10:32
  • Well, i had no idea such thing existed. But if you say it's easier. I might take a look into it. Commented Apr 20, 2016 at 11:44

2 Answers 2

1

You can use this

// declare an array
$json_array = array();
while ($row2 = mysqli_fetch_array($result2)) {
        // add this code
        $json_array[] = array(
            "{$row2['Straat']}",
            "{$row2['Noorderbreedte']}",
            "{$row2['Westerlengte']}",
            $row2['ID']
        );
        //echo '[' . $row2['Straat'] . ',' . $row2['Noorderbreedte'] . ',' . $row2['Westerlengte'] . ',' . $row2['ID'] . '],';
    }
?>
<script type="text/javascript">
var locations = <?php echo json_encode($json_array);?>
Sign up to request clarification or add additional context in comments.

2 Comments

Not yet, can I declare the PHP part in the javascript itself with php tags? The database objects don't get displayed on the google maps
Okay, it picks up the array and places it now, except the first one.
1

There's no need to invent a wheel. json_encode function will do what you need:

PHP:

$locations = array();
while ($row2 = mysqli_fetch_array($result2)) {
    $locations[] = array(
        $row2['Straat'],
        $row2['Noorderbreedte'], 
        $row2['Westerlengte'],
        $row2['ID']
    );
}

JS:

var locations = <? echo json_encode($locations)?>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.