jQuery serialize from datatables to PHP array without ajax - javascript

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?

Related

Manage form-data + other variable sent via ajax to php

My question is probably basic, but there is the question:
I have a javascript function which sends an array via ajax to process some information...
var second = $('form.contact').serialize();
var arry = {keystatus: varId, keyname: second}
In php, I added the data sent via ajax a array and wrote an echo to see in ajax success, displaying via console.log.
What do I get:
My php script:
$name = strip_tags($_POST['keystatus']);
$email = strip_tags($_POST['keyname']);
$teste['nome'] = $name;
$teste['email'] = $email;
echo json_encode($teste);
I needed to find a way to get separate, for example:
$_POST['keyname']['nome'] -> (in this example) discovery
$_POST['keyname']['email'] -> discovery#discovery.com
$_POST['keyname']['usuario'] -> discovery
You are currently adding the form data as a serialized string to an object, which you send. That's why it looks the way it does.
You can either build a new object with all data and send that object with ajax:
var data = {
keystatus: varId,
keyname: {
nome: $("#the_nome_input").val(),
email: $("#the_email_input").val(),
usuario: $("#the_usuario_input").val()
}
};
Or you can add the extra value (since it only seems to be one) as a hidden input field in your form:
// Add this to the form
<input type="hidden" value="" name="keystatus" id="keystatus" />
// In your js, add
$("#keystatus").val(varId); // Sets the value
var data = $("form.contact").serialize();
...now you can send data to your back end using ajax.
If you want to fetch your data like this: $_POST['keyname']['nome'] and use the second alternative, then you need to rename your input fields to: name="keyname[nome]", name="keyname[email]" and name="keyname[usuario]".
That will give you the correct data structure and values.

Can't unserialize full string

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

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

PHP returning empty POST array

JavaScript jQuery post:
var animals = {
animalsArray: [],
tripId: <?php echo $_GET['id']; ?>
};
$('.student-check').each(function() {
animals.animalsArray.push($(this).attr('id'));
});
var sendMe = JSON.stringify(animals);
$.post("saveChanges.php", sendMe, function(response) {
console.log(response);
}, "json");
PHP handler:
echo json_encode(print_r($_POST, true));
// Array
// (
// )
Why is the array empty? I'm posting data but the response returns an empty array.
You are encoding the data as JSON, which isn't a format PHP handles natively for form submissions.
Remove var sendMe = JSON.stringify(animals); and pass animals to $.post instead of sendMe. jQuery will encode it using one of the standard formats supported by HTML forms and PHP.
Alternatively see this question for how to get the raw request body.
Also:
echo json_encode(print_r($_POST, true));
json_encode and print_r are both functions that take a data structure and express it as a string. Use one or the other, not both.

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