Reputation: 1040
Have input form like <input type="text" name="record_date[] ...
Part of ajax that sends form to other php file is
var values = $("form").serialize();
$.ajax({
type: 'POST',
data: { 'Values' : values },
dataType: 'json',
The other php file receives data
$values = $_POST['Values'];
As understand this parse_str($_POST['Values'],$output);
creates array ($output
is array)
But with this print_r(json_encode($output));
I see nothing (expected to see array with values etc.)
If use echo json_encode($output['record_date']);
then all works and get entered values.
Trying to create array and then to use the array like this
foreach ($output as $i=>$output_value ) {
echo json_encode($output_value[$i]);
}
Changed to this echo json_encode($output_value['record_date'][$i]);
but in both case echo nothing.
As I understand main question is how to "modify/convert" parse_str($_POST['Values'],$output);
to php array
$_POST['Values']
looks like this: record_date%5B%5D=02.07.2013&record_date%5B%5D=01.07.2013
Possibly instead of parse_str
need to use something else
Update
If in ajax use dataType: 'json',
and in php
foreach ($output as $key => $output_value) {
echo json_encode($output_value);
}
then get nothing.
If commentdataType: 'json',
, then see ["02.07.2013","01.07.2013"].
If instead of echo json_encode($output_value);
use echo $output_value;
then see long list of ArrayArrayArrayArrayArray
.
If inside foreach
use var_dump($output_value);
then see like this
array(2) { [0]=> string(1) "2" [1]=> string(1) "6" }
...............
array(2) { [0]=> string(10) "02.07.2013" [1]=> string(10) "01.07.2013" }
Seems echo $output[$key][0]
inside foreach does what is necessary...
Finally made conclusion that must use such kind of code
foreach ($output[record_date] as $key => $output_value) {
echo $output_value. ' output value<br>';
echo $output[other_name_from_html_input][$key]. ' output date selector value<br>';
}
Upvotes: 0
Views: 350
Reputation: 10084
parse_str() actually does what you need.
parse_str($_POST['Values'], $output);
foreach ($output as $key => $output_value) {
echo json_encode($output_value);
}
Your problem was that you don't understand how foreach loop works. $output_value
is already value of the array element for current iteration, so you don't need to use it with indexes. If you want to use indexes you should use them with the original array like this:
foreach ($output as $key => $output_value) {
echo json_encode($output[$key]);
}
Read carefully: PHP: foreach
But there is something that confusing me. Why are you passing serialized form data as a single value, when you can pass it as post data itself? In this case you don't need to use parse_str()
and your code goes this:
JS:
var values = $("form").serialize();
$.ajax({
type: 'POST',
data: values,
dataType: 'json',
PHP:
foreach ($_POST as $value) {
echo json_encode($value);
}
Upvotes: 1