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});
Related
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);.
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>
<?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.
Currently I am using a jQuery Ajax asynchronous function to request a PHP page multiple times until a large number of spreadsheet rows are processed. Right now I am using the following code to set the variables to be passed to the requested page, I am not sure if this is the proper way to do it or not. PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
$new_spreadsheet = json_encode($new_spreadsheet);
echo var_dump($new_spreadsheet);
}
JavaScript/PHP:
var done = false,
offset = 0,
limit = 20,
rankings_abv_twenty = 0,
sum = 0,
num_count = 0,
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
On the requested PHP page (which happens to be Object-Oriented PHP), I have the following code to slice off 20 rows to process on the given request. Please not the PHP is a full working class, I just did not include all the PHP for the sake of post length. Also note, I have another page which calls the class, which passes the spreadsheet variable to the constructor of the PHP by reference as $_POST['spreadsheet'], so I know I have the right value as the spreadsheet. PHP:
$this->offset = $offset;
$this->limit = $limit;
$this->spreadsheet = json_decode($spreadsheet);
Here is the PHP line which slices off the rows:
$this->rows = array_slice($this->spreadsheet, $this->offset, $this->limit);
For some reason my code is not working properly and is giving me the following errors relating to the above code:
PHP Warning: json_decode() expects parameter 1 to be string, array given
PHP Warning: array_slice() expects parameter 1 to be array, null given
I think it might have something to do with how my string is getting passed the requested PHP. Also, just as a further note, when I use var_dump() on my spreadsheet variable before it is passed to the requested PHP, I get it outputted as a string like so:
string(7560) "String content goes here"
On the first look, instead of echoing the json_encode, you used var_dump.
And when manually modifying the json encoded string make sure to use " around the vars.
And this:
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
Will result in:
websites = 1, spreadsheet = "{"1":"foo","2":"bar","3":"baz","4":"blong"}";
Wrap the line in ' if that's what you expect it..
like this:
echo ", spreadsheet = '".$new_spreadsheet."'";
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...)