Pass result of SQL query from PHP to Javascript array - javascript

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);.

Related

Sending a PHP session variable to javascript of another file

I extracted data from a CSV file using PHP and stored the data as a nested array.
I stored this array as a session variable and now I want to access the array in another html file using javascript. How can this be done?
<?php
session_start();
$arr=array();
$arr['1']=array('abc','def');
$arr['2']=array('123','456');
$_SESSION["abc"]=$arr;
?>
This is a sample php. I have to access the session variable in javascript.
Yes, you can use implode PHP function to convert your array to string and then echo that string and assign to a JS variable like in example below.
Your another HTML file:
<?php
session_start();
$your_array=$_SESSION['your_array'];
?>
<script>
var js_variable = [<?php echo implode($your_array,','); ?>];
console.log(js_variable);
</script>
What you should be aware of, is that php is server side and javascript is client side. So to solve this, you have 2 options:
let the php code add this variables in the head. on to of everything:
<script>
var php_variables= <?php echo json_encode($your_php_variables); ?>;
</script>
or 2. Make a seperate php file which just echos only the value in json and put a json header:
<?php
header("content-type:application/json");
echo json_encode($your_php_variables);
?>
and then let javascript retrieve it. there are many libraries available for that. but lets take a comon one like jquery:
$.get("yourphpfile.php",function(data){do something here})

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>

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

Is json_encode extremely picky?

It appears that json_encode is being VERY picky about what other stuff can be inside my PHP file. Which is fine, because I just do what I normally would do in file A (with json_encode) in it's own file.
I just thought I would ask because I am storing a variable in the $_SESSION instead of updating my database with the variable because json_encode doesn't seem to want to work when I have all of the code in its file.
For instance, this code doesn't work:
<?php
session_start();
include 'dbcon.php';
$sessionID = uniqid();
echo json_encode($sessionID);
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
When going to the file in my browser, I do in fact get the json_encode results, however when my Javascript calls it it doesn't seem to correctly import it.
So, for now I simply have two PHP files:
<?php
session_start();
$sessionID = uniqid();
$_SESSION["sessionID"] = $sessionID;
echo json_encode($sessionID);
?>
Which echo's the same thing as in the first file, but this time my JavaScript correctly imports it.
and
<?php
session_start();
include 'dbcon.php';
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$sessionID = $_SESSION["sessionID"];
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
I guess my question is, why does this happen? It seems kind of silly that I have to store the uniqid in a SESSION so that my other PHP file can add it to the database. Whereas if I simply had it in one file, then I could just update the database when I generate a new uniqid and avoid having to use $_SESSION in the first place.
You have this:
$sessionID = uniqid();
echo json_encode($sessionID); // "53d4c17abfe87"
Since uniqid() produces a plain string, your output is not valid JSON as per the format specification. You'll need something like this instead:
$sessionID = uniqid();
echo json_encode(array($sessionID)); // ["53d4c17abfe87"]
Why does json_encode() generate invalid JSON in the first place? Because some times it's useful to generate partial JSON. For instance, it's a handy trick to inject values into generated JavaScript code:
var foo = <?=json_encode($sessionID)?>;
It's also documented:
PHP implements a superset of JSON - it will also encode and decode
scalar types and NULL. The JSON standard only supports these values
when they are nested inside an array or an object.
So to answer the question title:
Is json_encode extremely picky?
On the contrary, it's fairly relaxed!
You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.
So, what you would want would be something like this:
echo json_encode(array('sessionID' => $sessionID));
And then when you parse the JSON with JavaScript you can access it like this:
obj = JSON.parse(jsonObj);
alert(obj.sessionID);
Obviously, jsonObj is the JSON passed from the server.
Hope this helps!

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