Working with javascript array - javascript

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

Related

PHP json to a JavaScript variable inside an HTML file

I write the following script that creates a nice JSON of all the images under the current folder:
<?php
header('Content-type: application/json');
$output = new stdClass();
$pattern="/^.*\.(jpg|jpeg|png|gif)$/i"; //valid image extensions
$dirs = array_filter(glob('*'), 'is_dir');
foreach ($dirs as $dirname) {
$files = glob(''.$dirname.'/*');
$images = preg_grep($pattern, $files);
$output->{$dirname} = $images;
}
echo json_encode($output, JSON_PRETTY_PRINT);
?>
I have an HTML file with a basic page and I want to display the JSON's data in a formatted way after some javascript manipulation.
So the question is how can I get the PHP data into a javascript variable?
<html>
...
<body>
<script src="images.php"></script>
<script type="text/javascript">
// Desired: Get access to JSON $output
</script>
...
<div>
<img ... >
</div>
</body>
</html>
I tried to put both https://stackoverflow.com/a/61212271/1692261
and https://stackoverflow.com/a/50801851/1692261 inside that script tag but none of them work so I am guessing I am missing something fundamental here (my ever first experience with PHP :)
you should focus on what needs to be done, but currently you are trying to implement your own idea. maybe you should change your approach and do what you want in another way?
passing php variable to js is possible. but for what reason do you need this json? if you want to operate with it to generate html (f.e show images to user) you can do it on pure php without js. if you need exactly json you can generate json file with php and and get this file via additional js request. but the simplest way is
// below php code that generates json with images
$images = json_encode($output, JSON_PRETTY_PRINT);
...
// php code but in html template
<script type="text/javascript">
var images = "<?= $images ?>";
</script>
I won't guarantee that this js line is going to work but you get the idea)
P.S you dont need to use stdClass for such purposes. we do it via arrays (in you case it will be associative arrays), arrays are very powerful in php. json_encode() will generate same json from both array or object. but if this part of code works fine that let it stay as it is
I took #Zeusarm advice and just used ajax (and jquery) instead.
For others need a reference:
Nothing to change in PHP script in the original post.
Add jquery to the HTML file with <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Make a GET request like this:
<script type="text/javascript">
var images = ''
$.get('images.php',function (jsondata) {
images = jsondata
});
I am sure this is not the cleanest code but it works :)

How to place php variable in javascript object in different? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Executing PHP code inside a .js file
(5 answers)
Closed 2 years ago.
I am trying to fetch data from php, store it as json and load it into my javascript code.
I stored my variable in php like this:
$data = array[];
$data = json_encode($raw_data);
Now I want to retrieve that data and use it in my javascript file.
I tried to use the following code in my js file:
var data ="<?php echo $data ?>";
[screenshot]: https://i.stack.imgur.com/pDfsf.png
If the data is only needed once on page load, you can use a script bloc inside the PHP code and then use a JS function to fetch it. But if data is being updated according to the user's interaction with the page, keep in mind that you can't send data from server side in PHP to the client side in JS without using AJAX.
I suggest you read about and use one of these 3 methods:
XHR
fetch
or axios
You are declaring the string to the variable data by using quotes.
Please remove the quotes and that would behave as per your expectations.
So your code should be replaced by the below lines.
var data =<?php echo $data ?>;
var data = <?php echo $data ?>;
or
var data = JSON.parse("<?php echo $data ?>");
The most obvious problem is your quote marks, which make the variable a string in JavaScript, rather than a complex object with a data structure. So any references to properties etc in the variable would not work. The quote marks should be removed so that the data is rendered as an object literal into the emitted JavaScript.
But there's another signficant issue: if this is being done in a .js file as you state, then the PHP interpreter is not running there, so the echo won't work (quotes or no quotes), because it isn't executed by PHP and turned into data. You'd just see the PHP code directly embedded in the JS code.
You'd have to echo the data into a script block in the .php file, then call the appropriate function in your .js file and pass the data as a parameter. This will work nicely if the data is only needed once.
e.g.
PHP file
<?php
$data = array[];
$data = json_encode($raw_data);
?>
<script src="someJsFile.js"></script>
<script>
var data = <?php echo $data ?>; //inject the data into the JS as an object literal
someFunc(data); //pass the data to a function in someJsFile.js
</script>
JS file:
function someFunc(data) {
//your code to process the data
}
If you need to keep it updated during the lifetime of the page, then you'll need AJAX to be able to request new data from the server, as suggested in one of the other answers.

JSON from localstorage not able to decode in php

I am fetching values from localstorage as JSON and trying to decode.
But its not working.
This my code to fetch JSON from localstorage:
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
When i echoed above $items it resulted like this:
{"items":[{"name":"Guitar","id":"1"}]}
Decoding above json like this:
$decoded = json_decode($items, true);
When i am trying to echo $decoded not displaying anything. When i did var_dump($decoded) its showing NULL
Any help is appreciated. Thank you.
The situation is that you're not able to combine JS/PHP "in one line".
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
json_decode from $items will give you directly the code that you've put in (check json_last_error())... without any JS execution (or you have to use PhantomJS; but it's not your case).
How it has to be:
JS part (sample.js):
jQuery.post('sample.php', {
'item': JSON.stringify(localStorage.getItem('itemList'))
});
PHP part (sample.php)
$items = filter_input(INPUT_POST, 'item');
$decoded = json_decode($items, true);
var_dump($decoded);
localStorage only stores strings. The JSON.stringify() is wrong since it expects a JSON object, not a string, as input.

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

display json from php in javascript

I have a php file returning this valid Json data, stored in a javascript variable named "json".
[
"564654.56464",
"848492.25477",
"918821.54471"
]
I try to display it in javascript with :
var object = JSON.parse(json);
document.write(object. ..... );
i don't know what to add here since my Json is not like {"attribute":"value","attribute2":"value2"
You can encode your PHP file along with a json header. I guess that should do the trick!
header('Content-Type: application/json');
echo json_encode($array);
Use
document.write(object.toString());

Categories

Resources