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?
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 random
javascript php
add a comment |
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 random
javascript php
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
add a comment |
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 random
javascript php
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 random
javascript php
javascript php
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
add a comment |
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
add a comment |
3 Answers
3
active
oldest
votes
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; ?>
><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
add a comment |
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>
add a comment |
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))?>;
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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; ?>
><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
add a comment |
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; ?>
><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
add a comment |
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; ?>
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; ?>
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
add a comment |
><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
add a comment |
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>
add a comment |
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>
add a comment |
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>
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>
answered yesterday
rudakrudak
13512
13512
add a comment |
add a comment |
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))?>;
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
add a comment |
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))?>;
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
add a comment |
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))?>;
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))?>;
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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