how to keep running php part of index.php automatically? - javascript

I have an index.php that file contains php on top, then html and finally javascript. In my javascript part I get the values from my php part as follow:
var lati = <?php echo $valLat; ?>;
var longi = <?php echo $valLong; ?>;
and I use the lati and longi to update a marker on a map.
How can I keep calling the php part of my code with javascript in order to get the most recent latitude and longitude without having to update the webpage?
Here is my current php code it works but I have to reload the whole page to get the new latitude and longitude.
`
/* This part will select GPS_data database and it will get the most recent latitude and longitude values
these values are constantly updated in the database by a python file*/
//Selects GPS_data database.
mysql_select_db("GPS_data");
$sql = mysql_query("SELECT * FROM coordinates ORDER BY time DESC LIMIT 1"); //Gets the most recent lat and long.
$latitude = 'latitude'; //Set $latitude variable the same as the most recent latitude on the table.
$longitude = 'longitude';
$rows = mysql_fetch_assoc($sql);
$valLat = $rows['latitude'];
$valLong = $rows['longitude']; ?>

Minor changes to PHP file is required, plus some jQuery to retrieve lat/lon.
Changes:
Added an array $data to PHP code.
Stored lat and lon as elements of associated array to $data.
Converted PHP array to object usig json_encode.
Finally used echo, now $data will be available in jQuery as object.
Here is your modified PHP file.
<?
// fetch_latlon.php
/* This part will select GPS_data database and it will get the most recent latitude and longitude values
these values are constantly updated in the database by a python file*/
//Selects GPS_data database.
mysql_select_db("GPS_data");
$sql = mysql_query("SELECT * FROM coordinates ORDER BY time DESC LIMIT 1"); //Gets the most recent lat and long.
$latitude = 'latitude'; //Set $latitude variable the same as the most recent latitude on the table.
$longitude = 'longitude';
$rows = mysql_fetch_assoc($sql);
$valLat = $rows['latitude'];
$valLong = $rows['longitude'];
// I have added this
$data = [
'lat' => $valLat,
'lon' => $valLong
];
echo json_encode($data);
?>
Then in your HTML add AJAX code.
<script>
function updateLatLon() {
$.ajax({
// name of file to call
url: 'fetch_latlon.php',
// method used to call server-side code, this could be GET or POST
type: 'GET'
// Optional - parameters to pass to server-side code
data: {
key1: 'value1',
key2: 'value2',
key3: 'value3'
},
// return type of response from server-side code
dataType: "json"
// executes when AJAX call succeeds
success: function(data) {
// fetch lat/lon
var lat = data.lat;
var lon = data.lon;
// show lat/lon in HTML
$('#lat').text(lat);
$('#lon').text(lon);
},
// executes when AJAX call fails
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
}
// fetch lat/lon after each 3000 milliseconds
setTimeout(updateLatLon, 3000);
</script>
Side note: Convert your MySQL code to MySQLi because MySQL is deprecated.
For help in this conversion visit https://www.phpclasses.org/blog/package/9199/post/3-Smoothly-Migrate-your-PHP-Code-using-the-Old-MySQL-extension-to-MySQLi.html#convert
UPDATE
SOLVED Uncaught ReferenceError: $ is not defined
First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.
<script src="jquery.min.js"></script>
This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.
Then you need to use one of the two solutions below
(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code,
// or outside the document ready, enter code here
})(jQuery);
or
jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});
Please be aware that many times following code will not work, especially true in case of WordPress.
$(document).ready(function(){
//code here
});

You can use setTimeout javascript function in your code and use an ajax call to reload the variables you need. for example you can use jQuery get function to execute an ajax call.

Related

Convert WebStorage (JS/JQuery) content into Blade-ready variable

so I'm currently saving local data via WebStorage. Was wondering if there's a way to convert it to a Laravel Blade-ready variable upon page load. Here's what I've done so far.
$(document).ready(function () {
var data = JSON.parse(localStorage.getItem("data"));
// initialize php code
<?php $var = ?> data <?php ; ?>
});
However this doesnt work since it breaks PHP ruling

Sending a JavaScript variable to PHP, use said variable in an SQL statement, then display PHP results

I'm trying to send a JavaScript variable to a PHP script, use the variable in my SQL statement, and then send the results back to JavaScript.
JavaScript:
// Sending a variable to PHP script
var variableToSend = '30';
$.post('myPHPscript.php', {variable: variableToSend});
// Using the variable from earlier, run PHP script to get results
var data_from_ajax;
$.get('http://www.mywebsite.com/myPHPscript.php', function(data) {
data_from_ajax = data;
});
// Display results on the document
var displayResult = document.getElementById('displayResult');
displayResult.innerHTML = data_from_ajax;
PHP:
<?php
// Connection stuff
$conn = new mysqli($servername, $username, $password, $dbname);
// Get the sent variable
$variable = $_POST['variable'];
// Run SQL statement
$sql = "
SELECT column
FROM myDatabase
WHERE id=$variable
";
$result = $conn->query($sql);
// Send results back to JavaScript
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row["column"];
}
?>
The reason that JS is calling a PHP script is because I used an event listener in JS to determine the variable that I want to send. The variableToSend varies every time depending on what was clicked, but I have set it to some random number here.
I'm aware that the problem lies in sending variables to PHP scripts in the JavaScript, but I'm unsure how else I can do this, besides using .post and .get.
I also considered using an AJAX call, but I wasn't sure how that would work.
Thank you for any pointers.
You are already using ajax, twice, via $.post and $.get.
You only need to make the post request, and display the response:
// Sending a variable to PHP script via ajax post, and display the returned results
var variableToSend = '30';
$.post('http://www.mywebsite.com/myPHPscript.php', {variable: variableToSend}, function(responseFromPhp){
$('#displayResult').html(responsefromPhp);
});
The data you want will be returned on this post ajax call. To retrieve it specify success function.
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
and also use some validation and escaping before use post values in mysql:
http://php.net/manual/en/mysqli.real-escape-string.php

Populate map with data from SQL Database using Google Maps javascript API?

What I'm trying to do is to populate routes using the Google Maps API. I've written a working function that takes in any given array of lat/long values, I have a big database coordinates and I want to populate the map with a selection.
How can I get the data into JavaScript? So far I've got a button on the site and when pressed it runs a query that echoes what I need into some new page in JSON format:
$con = mysqli_connect("localhost","root","password","database");
$return_arr = array(); $result = mysqli_query($con,"SELECT * FROM
Flight_Data WHERE `DepDateTimeUTC` LIKE '%10/1/13%'");
while ($row = mysqli_fetch_array($result)) {
$row_array['ID'] = $row['ID'];
$row_array['OriginLat'] = $row['OriginLat'];
$row_array['OriginLong'] = $row['OriginLong'];
$row_array['DestinLat'] = $row['DestinLat'];
$row_array['DestinLong'] = $row['DestinLong'];
array_push($return_arr,$row_array); }
$jsonarray = json_encode($return_arr); echo $jsonarray;
This is a sample of the data:
[
{
"ID":"1",
"OriginLat":"48.6899",
"OriginLong":"9.2220",
"DestinLat":"37.014425",
"DestinLong":"-7.965910"
},
....
]
So I need to parse that into an array and be able to access each of the values like masterArray[1][4] etc.
So I'm stuck, the JavaScript is in a separate file, and so is the PHP script, I can put it in the same HTML page but I still don't know how to get it.
The best way would be to use an asynchronous (Ajax) query from your webpage, to pull the data down from your web server in Json format. The end result of this would be all of your data available in a JavaScript variable.
I would recommend using a library like jQuery to do this - have a look at the documentation here: http://api.jquery.com/jquery.ajax/
A basic (untested) example of doing this in jQuery would be:
<script>
$(document).ready(function() {
$.ajax("yourpage.php")
.done(function(data) {
mydata = data;
});
});
</script>

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Categories

Resources