Can't unserialize full string - javascript

Brief & Code
I have the content of a Chat log stored in a .txt file. The content is as follows:
a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"14:15:54";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 2";s:4:"time";s:8:"14:16:55";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 3";s:4:"time";s:8:"14:17:59";}
A jQuery function calls out to a page chatretrieve.php to collect the content of this file. The PHP file looks like this:
<?php
session_start();
$data = unserialize(file_get_contents('../sessions/chats/log_'.$_SESSION['chatCode'].'.txt'));
#exit(print_r($data));
$content = '';
for($i = 0; $i < count( $data ); $i++){
$content.='<div class="msgln">';
$content.='<div class="meta">';
$content.='<span class="name">'.$data[$i]['author'].'</span>';
$content.='<span class="time">'.$data[$i]['time'].'</span>';
$content.='</div>';
$content.='<div class="msg">'.stripslashes(htmlspecialchars($data[$i]['message'])).'</div>';
$content.='</div>';
}
return $content;
The relevant part of the jQuery function is as follows:
$.post('inc/chatretrieve.php').done(function(data) {
console.log(data);
});
The problem
When I comment out the exit(print_r($data)) part of the PHP page, the console returns only the first of the array variables in the .txt file:
Array
(
[author] => e297f
[message] => test
[time] => 14:15:54
)
1
As there are three messages in the .txt file (and retrieved with the file_get_contents() function), why can I only see the first line when I use the unserialize() function?

The issue is that your serialised data isn't valid:
'a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"14:15:54";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 2";s:4:"time";s:8:"14:16:55";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 3";s:4:"time";s:8:"14:17:59";}
Because this is three arrays it's unclear how to unserialise this (I'm surprised that PHP doesn't fail outright but instead returns the first object).
You will need to either store this as a serialised array or, alternatively find a way to split the file into sections for each message - this could probably be done on newlines or something similar.
e.g. Something like
<?php
//Note the added newlines.
$sez = 'a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"14:15:54";}
a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 2";s:4:"time";s:8:"14:16:55";}
a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:6:"test 3";s:4:"time";s:8:"14:17:59";}';
foreach(explode("\n",$sez) as $line){
$data = unserialize($line);
print_r($data);
}
Example here http://codepad.org/sq1SbhIz

Related

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.

Improve Page Performance, save PHP array on server?

is it possible to store a PHP-array to my server, right now it always gets created when someone reloads the page from a CSV file but that is unnecessary since the file only chances after each hour.
ATM, the page takes like 9 seconds to load, which is quite long. The CSV file has 10k+ rows with 9 elements per row, so it would be really good for performance if the server didn't have to process 100k elements for each user.
I already have a cronjob for downloading the csv file so it would be good if the parse command would be executed after the download finished, only once per hour.
cronjob:
<?php
function download_remote_file($file_url, $save_to) {
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
download_remote_file(<url here>, realpath(".") . '/dump.csv');
?>
and this happens with every reload of the page:
1st: Parse data to array
$url = 'dump.csv';
$csvData = file_get_contents($url);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$line = str_replace("\\", "\", $line);
$line = str_replace("#", "#", $line);
$array[] = str_getcsv($line);
2nd: pass array to Javascript
var array = <?php echo json_encode( $array ) ?>;
3rd: create HTML table
//some code
4th: initialise data table plugin
$(document).ready( function () {
createtable();
$('#scoreboard').DataTable( {
"iDisplayLength": 50,
language: {
decimal: ".",
},
"lengthMenu": false,
"bLengthChange": false
} );
} );
Is there something that could be done faster?
Like, as mentioned, save the php array server-side or maybe saving the JS array with the HTML table somehow?
-Innerwolf
After you parse your CSV, do this:
$file = fopen('/tmp/output.js', 'w');
fwrite($file, '<script type="text/javascript">');
fwrite($file, 'var array =');
fwrite($file, json_encode( $array ));
fwrite($file, ';');
fwrite($file, '</script>');
fclose($file);
copy('/path/to/script.js', '/path/to/script.js.bak');
move('/tmp/output.js', '/path/to/script.js');
Then, later on when you are outputting the HTML, you just need to stick in a:
<script type="text/javascript" src="/scripts/script.js">
in the header. People's browsers should cache it properly too. Note the copy and move -- you don't strictly need to make a backup copy, but you MUST use a move() to replace the 'live' script -- move() is atomic, more or less, and won't result in anyone getting a half-file.
Also, note that you'll need write permissions to where the script is -- there are ways to keep this pretty secure (not letting your PHP script write all over the hard drive), but that's out of scope here.
Since you mention getting the data on an hourly basis I suggest the following:
grab the CSV file with cron and store the data in a database on an hourly basis
configure your data tables component to use server side data
This way you won't force every user to download the entire array at once on every first page load.
The server side script only fetches the number of records that need to be displayed on that particular page in the table.

calling javascript method with a php retrieved argument

I have a javascript method in separate js file that I want to call from a HTML page with a php argument.
<?php
include "connection.php";
$selectedpatient = $_POST['patient_dropdown'];
$myquery = "SELECT * FROM `patient_info` patient_info.Name = '$selectedpatient' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
<script> data_arrival($_tempdata); </script>
And I defined the source for the javascript file in the HTML header. It displays two errors:
1) Parse error in the javascript file - that's understandable as I included the javascript file in header and the file gets executed before the php actually retrieves any data.
2) data_arrival method is undefined
How can I fix this ?? I want to pass the $tempdata (after its populated by php) to data_arrival method as an argument.
Thanks in advance !
First of all: it's PHP that's executed first, not JavaScript. It can't be the other way round in your example.
data_arrival is undefined... because either you haven't defined it at all, or because it is defined after it's called.
To pass the value from PHP to JavaScript in your case, you can use:
data_arrival(<?php echo $_tempdata; ?>);
It will generate something like:
data_arrival([a, b, c, d, ...]);
Of course, data_arrival function need to be defined prior to its execution.
Edit
And maybe it's good to use the same variable name: $_tempdata vs $tempdata.

jQuery serialize from datatables to PHP array without ajax

I have a table using Datatables. I have a setup pretty much like this link in the fact that I have form fields in the table and that they are submitted. I don't want to use ajax, I want to use the submit button.
This is part of my code:
$('#form').submit( function() {
var sData = $('input', oTable.fnGetNodes()).serialize ();
console.log(sData);
$('#form-values').val(sData);
} );
So I'm taking the serialized data and I'm putting it in a hidden input box with the id #form-values. Once I submit, In the server side I can get the serialized data with $_POST['form-values'] but of course... the data is serialized... I would want that data in an array so I can analyze it and insert some of them in a database.
I tried doing unserialize($_POST['form-values']) but it gives me the error Notice: unserialize(): Error at offset 0 of 1098 bytes in...
My serialized data looks like:
comments%5B56%5D=&comments%5B35%5D=&comments%5B12%5D=&comments%5B32%5D=
But I would want it to be:
Array ( [comments] => Array ( [56] => [35] => [12] => [32] =>
You can get just the atributes from a URL using parse_url()
Once you have that you can use parse_str() to convert them to variables, it works with multidimensional arrays too!
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
Try this:
$params = array();
parse_str($_GET, $params);
Why not to use parseJSON jQuery function?

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