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>
Related
I have a PHP file from which I am trying to retrieve results in JSON format and access it in another html page through AJAX get request. I'm able to access the entire data but I'm not been able to access the individual data fields of JSON data. Here is the actual data when printed on the console :
[{"id":"1","name":"Amit","age":"26"},{"id":"2","name":"Alka","age":"26"},
{"id":"3","name":"Pragati","age":"25"}]
Now, my question is how do I append only the name of the first entry of JSON data received ? data[0].name does not seem to work.
Here is my Javascript code :
<script>
// This script illustrates the use of load function in Jquery.
let btn = $('button');
btn.click(function(){
$.get("query.php", function(data, status){
console.log(data);
$('.dummy').append(data);
});
});
</script>
Here is how my 'query.php' file looks which is used to convert SQL query result into JSON format.
$myArray = array();
if ($result = $conn->query("SELECT * FROM sample")) {
while($row = $result->fetch_assoc()) {
$myArray[]=$row;
}
echo json_encode($myArray);
}
I am used to update a javaScript variable manually each day this way
<script>
var data = [
['Austria','IBM','8284927','UF93NV', '10'],
['Spain','Dell','1098193','MN87QA', '4'],
...
];
//rest of my code
<script>
I want to pass the values to this variable from an SQL query result using PHP so that I don't need to type several lines each day.
I have created this PHP file where I am connecting to my database and storing the result of the query in an array.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="*******";
$db="*******";
$user="*******";
$pass="*******";
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=*******;Port=1456", $user, $pass);
$sth = $dbDB->prepare("SELECT top 2 [Country],[Customer Name],[Purchase Number],[Part Number],[Qty] FROM *******");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
?>
It's working fine as you see below the result
Now I want to pass the values in the variable $result to my variable data inside the javaScript tag using jason_encode.
I added the following code in the same PHP file
<script type="text/javascript">
var data = <?php echo json_encode($result); ?>;
alert(data.toString());
</script>
But when I added the alert to see the value of my variable data I receive this
and my variable should be this way
var data = [
['Austria','Tech Data Service GmbH','3508224010','01HV707', '4'],
['Austria','Tech Data Service GmbH','3508314557','40M7578', '1']
];
Any advises please what am I missing ? Thank you.
The data is already there in your variable. To check how it your objects look like, you could use alert(JSON.stringify(data)).
The contents of your data variable won't be arrays in JavaScript as associative arrays in PHP are objects in JSON.
To get the result you want, the simplest solution would be to use $result = $sth->fetchAll(PDO::FETCH_NUM);.
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.
I know, I know, one is client side and one is server side. I had to use PHP to grab a few arrays of data and I'm passing this data in to Google Charts geomaps. E.g:
echo 'var data = google.visualization.arrayToDataTable([
["Country", "Popularity"],
';
foreach($countries as $key=>$val){
echo '["'.$key.'",'.$val.'],';
}
echo ']);
When a user clicks on one of the countries (using an event listener) on the map it puts this value into a variable:
var country = data.getValue(selectedItem.row, 0);
Now I need to pass this to the PHP array, so I can do something like:
if($country == country){
//do whatever
}
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var country = data.getValue(selectedItem.row, 0);
$.post('file.php', {country: country});
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...)