Populate JavaScript variables with PHP values2019 Community Moderator ElectionHow do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?What's the difference between using “let” and “var” to declare a variable in JavaScript?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

Preparing as much as possible of a cake in advance

Align equations with text before one of them

Naming Characters after Friends/Family

Remove object from array based on array of some property of that object

Can you run a ground wire from stove directly to ground pole in the ground

Rationale to prefer local variables over instance variables?

ESPP--any reason not to go all in?

How to chmod files that have a specific set of permissions

The (Easy) Road to Code

Drawing the Möbius band and the Klein bottle

What is "desert glass" and what does it do to the PCs?

Why aren't there more gauls like Obelix?

If nine coins are tossed, what is the probability that the number of heads is even?

Computing the volume of a simplex-like object with constraints

Does the US political system, in principle, allow for a no-party system?

What is better: yes / no radio, or simple checkbox?

Do natural melee weapons (from racial traits) trigger Improved Divine Smite?

How spaceships determine each other's mass in space?

What is the oldest European royal house?

The Key to the Door

Are there other characters in the Star Wars universe who had damaged bodies and needed to wear an outfit like Darth Vader?

Sundering Titan and basic normal lands and snow lands

Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?

PSPICE - must be 'I' or 'V' error



Populate JavaScript variables with PHP values



2019 Community Moderator ElectionHow do JavaScript closures work?What is the most efficient way to deep clone an object in JavaScript?Which “href” value should I use for JavaScript links, “#” or “javascript:void(0)”?How do I remove a property from a JavaScript object?Which equals operator (== vs ===) should be used in JavaScript comparisons?What's the difference between using “let” and “var” to declare a variable in JavaScript?How do I include a JavaScript file in another JavaScript file?What does “use strict” do in JavaScript, and what is the reasoning behind it?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?










1















This map.php page displays a table containing mongoDB documents which contain a time, latitude and longitude for coordinate readings.



It also uses the google API to show a location on a map (hardwired). I want to replace the lat/long being read by the google map script with the latitude/longitude of the table entry with the largest 'Time' value (aka the latest entry). I understand that you can write php echo statements straight into to get the values but as you can see I have a loop to get the table entries, is it realistic to do what I want here? PHP learner, absolute mongodb and javascript novice here. Thanks for any help!



EDIT: SOLVED, edited to working solution as per selected answer. thanks all.



 <!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */

</style>
</head>
<body>
<h3>Last Locations</h3>

<?php
//name of DB: muntean Name of collection:TestData
$user = "muntean";
require '/var/composer/vendor/autoload.php';
$manager = new MongoDBDriverManager("mongodb://localhost:27017");
$collection = new MongoDBCollection($manager, $user, 'testData');

$data = "<table style='border:1px solid red;";
$data .= "border-collapse:collapse' border='1px'>";
$data .= "<thead>";
$data .= "<tr>";
$data .= "<th>Time</th>";
$data .= "<th>Longitude</th>";
$data .= "<th>Latitude</th>";
$data .= "</tr>";
$data .= "</thead>";
$data .= "<tbody>";

try
$cursor = $collection->find();
$largest = 0;
foreach($cursor as $document)
if ($largest < $document["Time"])
$largest = $document["Time"];
$longitude = $document["Longitude"];
$latitude = $document["Latitude"];


$data .= "<tr>";
$data .= "<td>" . $document["Time"] . "</td>";
$data .= "<td>" . $document["Longitude"]."</td>";
$data .= "<td>" . $document["Latitude"]."</td>";
$data .= "</tr>";

$data .= "</tbody>";
$data .= "</table>";
echo $data;
catch(MongoException $mongoException)
print $mongoException;
exit;



?>

<!--The div element for the map -->
<div id="map"></div>
<script>
// Initialize and add the map
function initMap()
// The location of point
var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>
// The map, centered at point
var map = new google.maps.Map(
document.getElementById('map'), zoom: 12, center: point);
// The marker, positioned at point
var marker = new google.maps.Marker(position: point, map: map);

</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6CMFIF-m8Z_kNLUGT7HEVBew_wPLno7o&callback=initMap">
</script>

</body>
</html>


Locations randomWhat it looks like, map should be centered on the table datta though










share|improve this question



















  • 1





    Is that what you're looking for ? var my_var = <?php echo json_encode($my_var); ?>;

    – samb102
    yesterday











  • That is the format (json encoding is not always necessary as I understand?) but there is no specific 'my_var' to target that I can see. If I want to isolate the longitude for example would it be "var longitude = <?php echo json_encode($document["Longitude"]; ?>; ? That can't be fully right actually since that will change and is written for the find().

    – Jay.F
    yesterday












  • I guess so (with a closing parenthesis)

    – samb102
    yesterday















1















This map.php page displays a table containing mongoDB documents which contain a time, latitude and longitude for coordinate readings.



It also uses the google API to show a location on a map (hardwired). I want to replace the lat/long being read by the google map script with the latitude/longitude of the table entry with the largest 'Time' value (aka the latest entry). I understand that you can write php echo statements straight into to get the values but as you can see I have a loop to get the table entries, is it realistic to do what I want here? PHP learner, absolute mongodb and javascript novice here. Thanks for any help!



EDIT: SOLVED, edited to working solution as per selected answer. thanks all.



 <!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */

</style>
</head>
<body>
<h3>Last Locations</h3>

<?php
//name of DB: muntean Name of collection:TestData
$user = "muntean";
require '/var/composer/vendor/autoload.php';
$manager = new MongoDBDriverManager("mongodb://localhost:27017");
$collection = new MongoDBCollection($manager, $user, 'testData');

$data = "<table style='border:1px solid red;";
$data .= "border-collapse:collapse' border='1px'>";
$data .= "<thead>";
$data .= "<tr>";
$data .= "<th>Time</th>";
$data .= "<th>Longitude</th>";
$data .= "<th>Latitude</th>";
$data .= "</tr>";
$data .= "</thead>";
$data .= "<tbody>";

try
$cursor = $collection->find();
$largest = 0;
foreach($cursor as $document)
if ($largest < $document["Time"])
$largest = $document["Time"];
$longitude = $document["Longitude"];
$latitude = $document["Latitude"];


$data .= "<tr>";
$data .= "<td>" . $document["Time"] . "</td>";
$data .= "<td>" . $document["Longitude"]."</td>";
$data .= "<td>" . $document["Latitude"]."</td>";
$data .= "</tr>";

$data .= "</tbody>";
$data .= "</table>";
echo $data;
catch(MongoException $mongoException)
print $mongoException;
exit;



?>

<!--The div element for the map -->
<div id="map"></div>
<script>
// Initialize and add the map
function initMap()
// The location of point
var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>
// The map, centered at point
var map = new google.maps.Map(
document.getElementById('map'), zoom: 12, center: point);
// The marker, positioned at point
var marker = new google.maps.Marker(position: point, map: map);

</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6CMFIF-m8Z_kNLUGT7HEVBew_wPLno7o&callback=initMap">
</script>

</body>
</html>


Locations randomWhat it looks like, map should be centered on the table datta though










share|improve this question



















  • 1





    Is that what you're looking for ? var my_var = <?php echo json_encode($my_var); ?>;

    – samb102
    yesterday











  • That is the format (json encoding is not always necessary as I understand?) but there is no specific 'my_var' to target that I can see. If I want to isolate the longitude for example would it be "var longitude = <?php echo json_encode($document["Longitude"]; ?>; ? That can't be fully right actually since that will change and is written for the find().

    – Jay.F
    yesterday












  • I guess so (with a closing parenthesis)

    – samb102
    yesterday













1












1








1








This map.php page displays a table containing mongoDB documents which contain a time, latitude and longitude for coordinate readings.



It also uses the google API to show a location on a map (hardwired). I want to replace the lat/long being read by the google map script with the latitude/longitude of the table entry with the largest 'Time' value (aka the latest entry). I understand that you can write php echo statements straight into to get the values but as you can see I have a loop to get the table entries, is it realistic to do what I want here? PHP learner, absolute mongodb and javascript novice here. Thanks for any help!



EDIT: SOLVED, edited to working solution as per selected answer. thanks all.



 <!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */

</style>
</head>
<body>
<h3>Last Locations</h3>

<?php
//name of DB: muntean Name of collection:TestData
$user = "muntean";
require '/var/composer/vendor/autoload.php';
$manager = new MongoDBDriverManager("mongodb://localhost:27017");
$collection = new MongoDBCollection($manager, $user, 'testData');

$data = "<table style='border:1px solid red;";
$data .= "border-collapse:collapse' border='1px'>";
$data .= "<thead>";
$data .= "<tr>";
$data .= "<th>Time</th>";
$data .= "<th>Longitude</th>";
$data .= "<th>Latitude</th>";
$data .= "</tr>";
$data .= "</thead>";
$data .= "<tbody>";

try
$cursor = $collection->find();
$largest = 0;
foreach($cursor as $document)
if ($largest < $document["Time"])
$largest = $document["Time"];
$longitude = $document["Longitude"];
$latitude = $document["Latitude"];


$data .= "<tr>";
$data .= "<td>" . $document["Time"] . "</td>";
$data .= "<td>" . $document["Longitude"]."</td>";
$data .= "<td>" . $document["Latitude"]."</td>";
$data .= "</tr>";

$data .= "</tbody>";
$data .= "</table>";
echo $data;
catch(MongoException $mongoException)
print $mongoException;
exit;



?>

<!--The div element for the map -->
<div id="map"></div>
<script>
// Initialize and add the map
function initMap()
// The location of point
var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>
// The map, centered at point
var map = new google.maps.Map(
document.getElementById('map'), zoom: 12, center: point);
// The marker, positioned at point
var marker = new google.maps.Marker(position: point, map: map);

</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6CMFIF-m8Z_kNLUGT7HEVBew_wPLno7o&callback=initMap">
</script>

</body>
</html>


Locations randomWhat it looks like, map should be centered on the table datta though










share|improve this question
















This map.php page displays a table containing mongoDB documents which contain a time, latitude and longitude for coordinate readings.



It also uses the google API to show a location on a map (hardwired). I want to replace the lat/long being read by the google map script with the latitude/longitude of the table entry with the largest 'Time' value (aka the latest entry). I understand that you can write php echo statements straight into to get the values but as you can see I have a loop to get the table entries, is it realistic to do what I want here? PHP learner, absolute mongodb and javascript novice here. Thanks for any help!



EDIT: SOLVED, edited to working solution as per selected answer. thanks all.



 <!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */

</style>
</head>
<body>
<h3>Last Locations</h3>

<?php
//name of DB: muntean Name of collection:TestData
$user = "muntean";
require '/var/composer/vendor/autoload.php';
$manager = new MongoDBDriverManager("mongodb://localhost:27017");
$collection = new MongoDBCollection($manager, $user, 'testData');

$data = "<table style='border:1px solid red;";
$data .= "border-collapse:collapse' border='1px'>";
$data .= "<thead>";
$data .= "<tr>";
$data .= "<th>Time</th>";
$data .= "<th>Longitude</th>";
$data .= "<th>Latitude</th>";
$data .= "</tr>";
$data .= "</thead>";
$data .= "<tbody>";

try
$cursor = $collection->find();
$largest = 0;
foreach($cursor as $document)
if ($largest < $document["Time"])
$largest = $document["Time"];
$longitude = $document["Longitude"];
$latitude = $document["Latitude"];


$data .= "<tr>";
$data .= "<td>" . $document["Time"] . "</td>";
$data .= "<td>" . $document["Longitude"]."</td>";
$data .= "<td>" . $document["Latitude"]."</td>";
$data .= "</tr>";

$data .= "</tbody>";
$data .= "</table>";
echo $data;
catch(MongoException $mongoException)
print $mongoException;
exit;



?>

<!--The div element for the map -->
<div id="map"></div>
<script>
// Initialize and add the map
function initMap()
// The location of point
var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>
// The map, centered at point
var map = new google.maps.Map(
document.getElementById('map'), zoom: 12, center: point);
// The marker, positioned at point
var marker = new google.maps.Marker(position: point, map: map);

</script>
<!--Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
-->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6CMFIF-m8Z_kNLUGT7HEVBew_wPLno7o&callback=initMap">
</script>

</body>
</html>


Locations randomWhat it looks like, map should be centered on the table datta though







javascript php






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday







Jay.F

















asked yesterday









Jay.FJay.F

518




518







  • 1





    Is that what you're looking for ? var my_var = <?php echo json_encode($my_var); ?>;

    – samb102
    yesterday











  • That is the format (json encoding is not always necessary as I understand?) but there is no specific 'my_var' to target that I can see. If I want to isolate the longitude for example would it be "var longitude = <?php echo json_encode($document["Longitude"]; ?>; ? That can't be fully right actually since that will change and is written for the find().

    – Jay.F
    yesterday












  • I guess so (with a closing parenthesis)

    – samb102
    yesterday












  • 1





    Is that what you're looking for ? var my_var = <?php echo json_encode($my_var); ?>;

    – samb102
    yesterday











  • That is the format (json encoding is not always necessary as I understand?) but there is no specific 'my_var' to target that I can see. If I want to isolate the longitude for example would it be "var longitude = <?php echo json_encode($document["Longitude"]; ?>; ? That can't be fully right actually since that will change and is written for the find().

    – Jay.F
    yesterday












  • I guess so (with a closing parenthesis)

    – samb102
    yesterday







1




1





Is that what you're looking for ? var my_var = <?php echo json_encode($my_var); ?>;

– samb102
yesterday





Is that what you're looking for ? var my_var = <?php echo json_encode($my_var); ?>;

– samb102
yesterday













That is the format (json encoding is not always necessary as I understand?) but there is no specific 'my_var' to target that I can see. If I want to isolate the longitude for example would it be "var longitude = <?php echo json_encode($document["Longitude"]; ?>; ? That can't be fully right actually since that will change and is written for the find().

– Jay.F
yesterday






That is the format (json encoding is not always necessary as I understand?) but there is no specific 'my_var' to target that I can see. If I want to isolate the longitude for example would it be "var longitude = <?php echo json_encode($document["Longitude"]; ?>; ? That can't be fully right actually since that will change and is written for the find().

– Jay.F
yesterday














I guess so (with a closing parenthesis)

– samb102
yesterday





I guess so (with a closing parenthesis)

– samb102
yesterday












3 Answers
3






active

oldest

votes


















1














Into the PHP loop you can save the Longitude and Latitude with the largest time value, like :



$largest = 0;
foreach($cursor as $document)
if ($largest < $document["Time"])
$largest = $document["Time"];
$longitude = $document["Longitude"];
$latitude = $document["Latitude"];


$data .= "<tr>";
$data .= "<td>" . $document["Time"] . "</td>";
$data .= "<td>" . $document["Longitude"]."</td>";
$data .= "<td>" . $document["Latitude"]."</td>";
data .= "</tr>";



After you can echo $longitude and $latitude into your javascript



var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>





share|improve this answer

























  • ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

    – Jay.F
    yesterday











  • PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

    – Jay.F
    yesterday











  • I think i already tried putting it in a try/catch maybe it just needs to be declared.

    – Jay.F
    yesterday







  • 1





    Put the if statement into your loop and don't create another loop.

    – R3tep
    yesterday


















2














you just have to encode your variables in Json in PHP to get a string with JS. then you decode the Json and you will have your variables in a nice JS object



<script>
let json= "<?php echo json_encode($variables); ?>";
let obj = JSON.parse(json);
</script>





share|improve this answer






























    1














    There are two steps here :



    • Get the document with the latest data

    • Insert the values into your JS

    For the first one, you can take advantage of the loop you already have if performance is an issue (thousands of time frames), but for cleaner code, I would suggest declaring a dedicated function in your PHP:



    /**
    * Returns the latest data in a collection, or false if none exists
    */
    function getLatestData($collection)
    $cursor = $collection->find();
    $result = null;
    foreach ($cursor as $document) $document['Time'] > $result['Time'])
    $result = $document;


    if ($result !== null)
    return ['lat' => $result['Latitude'], 'lng' => $result['Longitude']];

    return false;



    Then, inside your JS, you can use json_encode to convert your result into a JSON string:



    var point = <?=json_encode(getLatestData($collection))?>;





    share|improve this answer

























    • Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

      – Jay.F
      yesterday











    • <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

      – Jay.F
      yesterday











    • p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

      – Jay.F
      yesterday






    • 1





      Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

      – blex
      yesterday










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55019162%2fpopulate-javascript-variables-with-php-values%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Into the PHP loop you can save the Longitude and Latitude with the largest time value, like :



    $largest = 0;
    foreach($cursor as $document)
    if ($largest < $document["Time"])
    $largest = $document["Time"];
    $longitude = $document["Longitude"];
    $latitude = $document["Latitude"];


    $data .= "<tr>";
    $data .= "<td>" . $document["Time"] . "</td>";
    $data .= "<td>" . $document["Longitude"]."</td>";
    $data .= "<td>" . $document["Latitude"]."</td>";
    data .= "</tr>";



    After you can echo $longitude and $latitude into your javascript



    var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>





    share|improve this answer

























    • ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

      – Jay.F
      yesterday











    • PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

      – Jay.F
      yesterday











    • I think i already tried putting it in a try/catch maybe it just needs to be declared.

      – Jay.F
      yesterday







    • 1





      Put the if statement into your loop and don't create another loop.

      – R3tep
      yesterday















    1














    Into the PHP loop you can save the Longitude and Latitude with the largest time value, like :



    $largest = 0;
    foreach($cursor as $document)
    if ($largest < $document["Time"])
    $largest = $document["Time"];
    $longitude = $document["Longitude"];
    $latitude = $document["Latitude"];


    $data .= "<tr>";
    $data .= "<td>" . $document["Time"] . "</td>";
    $data .= "<td>" . $document["Longitude"]."</td>";
    $data .= "<td>" . $document["Latitude"]."</td>";
    data .= "</tr>";



    After you can echo $longitude and $latitude into your javascript



    var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>





    share|improve this answer

























    • ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

      – Jay.F
      yesterday











    • PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

      – Jay.F
      yesterday











    • I think i already tried putting it in a try/catch maybe it just needs to be declared.

      – Jay.F
      yesterday







    • 1





      Put the if statement into your loop and don't create another loop.

      – R3tep
      yesterday













    1












    1








    1







    Into the PHP loop you can save the Longitude and Latitude with the largest time value, like :



    $largest = 0;
    foreach($cursor as $document)
    if ($largest < $document["Time"])
    $largest = $document["Time"];
    $longitude = $document["Longitude"];
    $latitude = $document["Latitude"];


    $data .= "<tr>";
    $data .= "<td>" . $document["Time"] . "</td>";
    $data .= "<td>" . $document["Longitude"]."</td>";
    $data .= "<td>" . $document["Latitude"]."</td>";
    data .= "</tr>";



    After you can echo $longitude and $latitude into your javascript



    var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>





    share|improve this answer















    Into the PHP loop you can save the Longitude and Latitude with the largest time value, like :



    $largest = 0;
    foreach($cursor as $document)
    if ($largest < $document["Time"])
    $largest = $document["Time"];
    $longitude = $document["Longitude"];
    $latitude = $document["Latitude"];


    $data .= "<tr>";
    $data .= "<td>" . $document["Time"] . "</td>";
    $data .= "<td>" . $document["Longitude"]."</td>";
    $data .= "<td>" . $document["Latitude"]."</td>";
    data .= "</tr>";



    After you can echo $longitude and $latitude into your javascript



    var point = lat: <?php echo $latitude; ?>, lng: <?php echo $longitude; ?>






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    R3tepR3tep

    7,42182862




    7,42182862












    • ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

      – Jay.F
      yesterday











    • PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

      – Jay.F
      yesterday











    • I think i already tried putting it in a try/catch maybe it just needs to be declared.

      – Jay.F
      yesterday







    • 1





      Put the if statement into your loop and don't create another loop.

      – R3tep
      yesterday

















    • ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

      – Jay.F
      yesterday











    • PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

      – Jay.F
      yesterday











    • I think i already tried putting it in a try/catch maybe it just needs to be declared.

      – Jay.F
      yesterday







    • 1





      Put the if statement into your loop and don't create another loop.

      – R3tep
      yesterday
















    ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

    – Jay.F
    yesterday





    ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody></ta ble>

    – Jay.F
    yesterday













    PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

    – Jay.F
    yesterday





    PHP Fatal error: Uncaught exception 'MongoDBDriverExceptionLogicExceptio n' with message 'Cursors cannot yield multiple iterators' in /home/muntean/www/m ap.php:52 Stack trace: #0 /home/muntean/www/map.php(52): unknown() #1 main thrown in /home/muntean/www/map.php on line 52

    – Jay.F
    yesterday













    I think i already tried putting it in a try/catch maybe it just needs to be declared.

    – Jay.F
    yesterday






    I think i already tried putting it in a try/catch maybe it just needs to be declared.

    – Jay.F
    yesterday





    1




    1





    Put the if statement into your loop and don't create another loop.

    – R3tep
    yesterday





    Put the if statement into your loop and don't create another loop.

    – R3tep
    yesterday













    2














    you just have to encode your variables in Json in PHP to get a string with JS. then you decode the Json and you will have your variables in a nice JS object



    <script>
    let json= "<?php echo json_encode($variables); ?>";
    let obj = JSON.parse(json);
    </script>





    share|improve this answer



























      2














      you just have to encode your variables in Json in PHP to get a string with JS. then you decode the Json and you will have your variables in a nice JS object



      <script>
      let json= "<?php echo json_encode($variables); ?>";
      let obj = JSON.parse(json);
      </script>





      share|improve this answer

























        2












        2








        2







        you just have to encode your variables in Json in PHP to get a string with JS. then you decode the Json and you will have your variables in a nice JS object



        <script>
        let json= "<?php echo json_encode($variables); ?>";
        let obj = JSON.parse(json);
        </script>





        share|improve this answer













        you just have to encode your variables in Json in PHP to get a string with JS. then you decode the Json and you will have your variables in a nice JS object



        <script>
        let json= "<?php echo json_encode($variables); ?>";
        let obj = JSON.parse(json);
        </script>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        rudakrudak

        13512




        13512





















            1














            There are two steps here :



            • Get the document with the latest data

            • Insert the values into your JS

            For the first one, you can take advantage of the loop you already have if performance is an issue (thousands of time frames), but for cleaner code, I would suggest declaring a dedicated function in your PHP:



            /**
            * Returns the latest data in a collection, or false if none exists
            */
            function getLatestData($collection)
            $cursor = $collection->find();
            $result = null;
            foreach ($cursor as $document) $document['Time'] > $result['Time'])
            $result = $document;


            if ($result !== null)
            return ['lat' => $result['Latitude'], 'lng' => $result['Longitude']];

            return false;



            Then, inside your JS, you can use json_encode to convert your result into a JSON string:



            var point = <?=json_encode(getLatestData($collection))?>;





            share|improve this answer

























            • Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

              – Jay.F
              yesterday











            • <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

              – Jay.F
              yesterday











            • p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

              – Jay.F
              yesterday






            • 1





              Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

              – blex
              yesterday















            1














            There are two steps here :



            • Get the document with the latest data

            • Insert the values into your JS

            For the first one, you can take advantage of the loop you already have if performance is an issue (thousands of time frames), but for cleaner code, I would suggest declaring a dedicated function in your PHP:



            /**
            * Returns the latest data in a collection, or false if none exists
            */
            function getLatestData($collection)
            $cursor = $collection->find();
            $result = null;
            foreach ($cursor as $document) $document['Time'] > $result['Time'])
            $result = $document;


            if ($result !== null)
            return ['lat' => $result['Latitude'], 'lng' => $result['Longitude']];

            return false;



            Then, inside your JS, you can use json_encode to convert your result into a JSON string:



            var point = <?=json_encode(getLatestData($collection))?>;





            share|improve this answer

























            • Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

              – Jay.F
              yesterday











            • <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

              – Jay.F
              yesterday











            • p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

              – Jay.F
              yesterday






            • 1





              Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

              – blex
              yesterday













            1












            1








            1







            There are two steps here :



            • Get the document with the latest data

            • Insert the values into your JS

            For the first one, you can take advantage of the loop you already have if performance is an issue (thousands of time frames), but for cleaner code, I would suggest declaring a dedicated function in your PHP:



            /**
            * Returns the latest data in a collection, or false if none exists
            */
            function getLatestData($collection)
            $cursor = $collection->find();
            $result = null;
            foreach ($cursor as $document) $document['Time'] > $result['Time'])
            $result = $document;


            if ($result !== null)
            return ['lat' => $result['Latitude'], 'lng' => $result['Longitude']];

            return false;



            Then, inside your JS, you can use json_encode to convert your result into a JSON string:



            var point = <?=json_encode(getLatestData($collection))?>;





            share|improve this answer















            There are two steps here :



            • Get the document with the latest data

            • Insert the values into your JS

            For the first one, you can take advantage of the loop you already have if performance is an issue (thousands of time frames), but for cleaner code, I would suggest declaring a dedicated function in your PHP:



            /**
            * Returns the latest data in a collection, or false if none exists
            */
            function getLatestData($collection)
            $cursor = $collection->find();
            $result = null;
            foreach ($cursor as $document) $document['Time'] > $result['Time'])
            $result = $document;


            if ($result !== null)
            return ['lat' => $result['Latitude'], 'lng' => $result['Longitude']];

            return false;



            Then, inside your JS, you can use json_encode to convert your result into a JSON string:



            var point = <?=json_encode(getLatestData($collection))?>;






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited yesterday

























            answered yesterday









            blexblex

            12.3k12245




            12.3k12245












            • Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

              – Jay.F
              yesterday











            • <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

              – Jay.F
              yesterday











            • p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

              – Jay.F
              yesterday






            • 1





              Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

              – blex
              yesterday

















            • Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

              – Jay.F
              yesterday











            • <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

              – Jay.F
              yesterday











            • p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

              – Jay.F
              yesterday






            • 1





              Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

              – blex
              yesterday
















            Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

            – Jay.F
            yesterday





            Thank you. var point = <?=json_encode(getLatestData($collection))?>; is being read as "var point = true". Is this meant to be complete code?

            – Jay.F
            yesterday













            <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

            – Jay.F
            yesterday





            <tbody><tr ><td>1551849760</td><td>-6.602801322937</td><td>53.3740234375</td></tr><tr><td>1 551854433</td><td>-6.6027488708496</td><td>53.374073028564</td></tr></tbody><

            – Jay.F
            yesterday













            p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

            – Jay.F
            yesterday





            p.s I assume it's supposed to be "$result = $document;"? rather than "$result = document;"?

            – Jay.F
            yesterday




            1




            1





            Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

            – blex
            yesterday





            Sorry, I write JS every day, and messed up while writing this PHP piece. I fixed it. I see you've found another answer, though ;-)

            – blex
            yesterday

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55019162%2fpopulate-javascript-variables-with-php-values%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

            Алба-Юлія

            Захаров Федір Захарович