简体   繁体   中英

Max of values in 2 PHP variables, how to pass from script to jQuery?

I want to use gmaps.js to add map markers onto a map on my site. I'm using a PHP Script to get the latitude and longitude from my DB, however I'm using

while($dbrowinfo = mysqli_fetch_assoc($rowfields))

Therefore the information comes to an end after the Database query has been ran. Per page there will be a maximum of 10 sets of data, both with a long and lat value (therefore 20 individual variables).

Is there any way to use the variables from PHP to pass to jQuery before the script is ran? Can't really get my head around it as jQuery is client and PHP is serverside...

Thanks for your time

If you are asking if there is a way to pass variables from PHP to JavaScript before the JQuery script has run, the answer is yes, definitely. All the PHP will run before any of the JavaScript, so, you can simply output the data you want as JavaScript variables, like so:

<html>

<?php
// Load the data into your PHP variables
$dataA = "some data";
$dataB = "some more data";
$dataC = 245; // numeric data
?>
<body>
    <!-- now open a script tag -->
    <script>
    var jsVar1 = "<?= $dataA ?>";// If outputting string, you need to add quotes for js
    var jsVar2 = "<?= $dataB ?>"; 
    var jsVar3 = <?= $dataC ?>; // No quotes needed for a number

    $(document).ready(function(){
        console.log("data from php: " + jsVar1 + " " + jsVar2 + " " + jsVar3);
    });
    </script>
</body>

</html>

Put the values in a PHP array, and then encode them into a Javascript array with json_encode

$coords = array();
while ($row = mysqli_fetchassoc($rowfields)) {
    $coords[] = array('lat' => $row['lat'], 'lng' => $row['lng']);
}
echo '<script>var coords = ' . json_encode($coords) . ';</script>';

This defines a Javascript variable coords that contains an array of objects, like:

var coords = [
    { lat: 50.0, lng: 101.1 },
    { lat: -20.8, lng: 55.3 },
    ...
];

You can then use this array in your jQuery code.

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