I have various forms in a single page.
All the forms get submitted by the below jQuery function.
All is ok, but there is a specific form that has duplicated input names.
In fact in this form the inputs get cloned on request.
So for example, this form represents how many people attend an event.
The user can add as many people as he wants and adding details of each by filling the form.
The inputs get cloned on the fly and inserted inside the form.
The problem is that jQuery is sending them in the wrong way, like shown below, and my php code is not responding well. In fact it just sees one of the posted "people" instead that them all.
Example of jquery post:
protagonist_description zxcvvcbhcvbjfg
protagonist_description jfghjfghjh
protagonist_email
protagonist_email
protagonist_name zxcvzxcv
protagonist_name dfghdfgh
protagonist_phone
protagonist_phone
protagonist_role zxcvxzcv
protagonist_role hgfjgfhjhgh
protagonist_surname zcxvzxcv
protagonist_surname dfghd
protagonist_video
protagonist_video
protagonist_website
protagonist_website
Example of PHP response:
Array
(
[protagonist_name] => dfghdfgh
[protagonist_surname] => dfghd
[protagonist_role] => hgfjgfhjhgh
[protagonist_description] => jfghjfghjh
[protagonist_email] =>
[protagonist_phone] =>
[protagonist_website] =>
[protagonist_video] =>
)
As you see it just gets the last posted.
Here is my jQuery function:
$(".save").click(function() {
$.ajax({
type: 'POST',
data: $('form[name="wizard_form"]').serialize(),
success: function() {
$('#publish').modal('show');
}
});
});
Please note that all the cloned inputs are inside the same form.
I can only use one form. So please do not suggest using more cloned forms. It won't work for my code as it is.
I am looking for a way to correctly merge the inputs with the same name in specific arrays posted to the PHP code.
How to do that?
You first need to change your form inputs to be arrays by adding [] to the name like so:
<input name="protagonist_description[]" />
And then in your PHP it will look like this:
Array
(
[protagonist_name] => Array
(
[0] => zxcvzxcv,
[1] => dfghdfgh,
)
[protagonist_surname] => Array
(
[0] => zcxvzxcv,
[1] => dfghd,
)
[protagonist_role] => Array
(
[0] => zxcvxzcv,
[1] => hgfjgfhjhgh,
)
[protagonist_description] => Array
(
[0] => zxcvvcbhcvbjfg,
[1] => jfghjfghjh,
)
[protagonist_email] => Array
(
[0] => ,
[1] => ,
)
[protagonist_phone] => Array
(
[0] => ,
[1] => ,
)
[protagonist_website] => Array
(
[0] => ,
[1] => ,
)
[protagonist_video] => Array
(
[0] => ,
[1] => ,
)
)
At this point you can then loop through the values like this:
for ($i = 0, $max = count($_POST['protagonist_name']); $i < $max; $i++) {
$first_protagonist = array(
'protagonist_name' => $_POST['protagonist_name'][$i],
'protagonist_surname' => $_POST['protagonist_surname'][$i],
// ...
);
}
Per David's suggestion, here's the code for a foreach if you wish:
foreach ($_POST['protagonist_name'] as $key => $val) {
$first_protagonist = array(
'protagonist_name' => $val,
'protagonist_surname' => $_POST['protagonist_surname'][$key],
'protagonist_description' => $_POST['protagonist_description'][$key],
// ...
);
}
You need to add brackets to your input's name.
Example:
<input name="my_name[]" value="david" />
<input name="my_name[]" value="john" />
<input name="my_name[]" value="francis" />
$_POST['my_name'] will be an array containing all results.
Array
(
[my_name] => Array
(
[0] => david
[1] => john
[2] => francis
)
)
To handle arrays of input elements, in other words defined as having the same element name. If you define the name with two square brackets in the end it will be transformed to an array on the server side for php.
<input type='text' name='elmname[]' .....
<input type='text' name='elmname[]' .....
if you submit the form consisting these elements and then on the php side you will see that $_POST['elmname'] will be an array
Related
I have an array like this:
Array
(
[action_name] => edit
[formData] => color=red&size=full&symmetry=square&symmetry=circle&symmetry=oval
)
Here, form data is coming using the serialize method of JS and so it is displayed like above. I want to get each data from the formData key. How can I get that?
I tried:
$_POST['formData']['color']
But that is not working. I think the method to fetch this shall be different. How can I do that?
You can use parse_​str to "parse string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided)."
<?php
$_POST = [
'action_name' => 'edit',
'formData' => 'color=red&size=full&symmetry=square',
];
parse_str($_POST['formData'], $parsed);
print_r($parsed);
will output
Array
(
[color] => red
[size] => full
[symmetry] => square
)
Edit:
Having multiple values for symmetry, your query should look like:
<?php
$_POST = [
'action_name' => 'edit',
'formData' => 'color=red&size=full&symmetry[]=square&symmetry[]=circle&symmetry[]=oval',
];
parse_str($_POST['formData'], $parsed);
print_r($parsed);
This would output:
Array
(
[color] => red
[size] => full
[symmetry] => Array
(
[0] => square
[1] => circle
[2] => oval
)
)
I am new with php and I want to get form data in php from jQuery serialize array. In php I am not able to get this data in proper format.
Here how I am passing this data from jquery
var form_data = jQuery(this).serializeArray();
form_data = JSON.stringify(form_data);
In php I have implemented json_decode function but I am still getting this array in not useful format.
$data = json_decode(stripslashes($_POST['data']),true);
It is returning form data in this format
Array
(
[0] => Array
(
[name] => fname
[value] => MyFirstName
)
[1] => Array
(
[name] => lname
[value] => MyLastName
)
[2] => Array
(
[name] => phone
[value] => 324242
)
[3] => Array
(
[name] => institution_name[]
[value] => institution
)
[4] => Array
(
[name] => degree_name[]
[value] => Graduated
)
How I can get data properly from this array so that I can use this properly. There are more then 50 input fields in my form and I have few fields like degree_name[] so there can be more then one degree_name[] input fields so how I will be able to fetch data when I will have multiple input fields with the same name. I will appreciate your help.
I think what you're looking for if I'm reading the question right is:
$data = json_decode(stripslashes($_POST['data']),true);
foreach($data as $row) {
echo "{$row['name']}: {$row['value']}";
}
for multiple input fields with the same name
use array name in input field,
for example:
<input name="degree_name[]" type="text">
By default, Gravity Form merge tags for checkboxes output the value of the selected option. If they choices for a question are English, Spanish, and Other, and the user selects English, the merge tag outputs:
english
My end goal is to be able to customize a Gravity Form merge tag output for checkboxes to include all of the options, checkbox-like format, and the selected option (checkbox is checked).
Right now, I'm trying to at least be able to return all of the options. Using this function,
`
add_action( 'gform_pre_submission_3', 'pre_submission_handler' );
function pre_submission_handler( $form ) {
foreach($form['fields'] as &$field) {
if($field['id'] === 13) {
//$selectData['inputs'] = $field['inputs'];
$selectData['selections'] = $field['choices'];
$the_fields = $selectData;
foreach ($the_fields as $fields) {
print_r($fields);
}
}
}
I can get an output:
Array (
[0] => Array (
[text] => English
[value] => Language: English
[isSelected] =>
[price] =>
)
[1] => Array (
[text] => Spanish
[value] => Language: Spanish
[isSelected] =>
[price] =>
)
[2] => Array (
[text] => Other (specify)
[value] => Other
[isSelected] =>
[price] =>
)
)
I think that I'm going to need to get the [text] for each of the sub arrays into a new array. What's the syntax like to do that?
With the new array, I will be able to do a foreach loop, wrapping each element in HTML, using CSS to style the output like a checkbox.
As shorty:
$new_array = array_map(function($a){return $a['text'];},$fields);
;)
I'm creating a class that assists in building settings pages for WordPress plugins. The developer instantiates the class by passing in an array of settings. A basic example looks like:
Array
(
[textbox1] => Array
(
[title] => Textbox
[type] => text
[section] => general
[desc] => The text description
)
[a_nice_dropdown] => Array
(
[title] => Select me
[type] => select
[section] => general
[desc] => The select description
[choices] => Array
(
[red] => Red
[blue] => Blue
[green] => Green
)
)
)
This works fine. My class builds the options page and the inputs have HTML that looks like:
<input id="textbox1" type="text" name="options_slug[textbox1]" value="">
When "Save Changes" is clicked, my class grabs all the options tied to "options_slug" and stores them in a single wp_options entry as a nice serialized array, making it easy to grab later.
The New Challenge
I have a new project which requires multiple nested "repeater" fields, similar to the way Advanced Custom Fields handles it. I've created a new field type, to handle this, which can support "subfields". An example config output (from error_log) looks like:
Array
(
[subfields_container] => Array
(
[title] => Subfields
[type] => subfields
[section] => general
[desc] => This is the subfields description text
[subfields] => Array
(
[textbox2] => Array
(
[title] => Textbox
[type] => text
[section] => general
[desc] => The text description
)
[select1deep] => Array
(
[title] => Subfield Select
[type] => select
[choices] => Array
(
[1] => 1
[2] => 2
[3] => 3
)
[std] => 1
)
)
)
)
I've configured the HTML output so an input inside a "subfields" container now looks like:
<input id="textbox1" type="text" name="options_slug[subfields_container][textbox2]" value="">
The idea being that the end user can easily group fields: i.e.,
$options = get_option('options_slug');
foreach($options['subfield_container'] as $subfield) {
// etc...
}
The Problem
As I iterate through these multidimensional arrays, I need to continually update a $options variable at the current index so it can be saved to the DB. So where previously I was able to do:
$id = 'textbox1';
$options[$id] = $_POST['textbox1'];
Now I'm doing something like:
$id = array('subfields_container' => 'textbox2');
$options[$id] = $_POST['textbox2'];
But I get "illegal offset type" errors. Because I can't set an array property using another array.
I've considered just putting dashes in the ID's instead of creating a hierarchical array, something like:
<input id="textbox1" type="text" name="options_slug[subfields_container-textbox2]" value="">
But then I'll lose the ability to foreach over a specific part of the stored options.
The Question
What's the best way to dynamically set a value inside of a multidimensional array when the array is not fixed in structure?
Thank you
I'd suggest to just dynamically create a multi-leveled array:
$arr = array();
$arr['subfields_container']['textbox1'] = $_POST['textbox1'];
print_r($arr);
=>
Array
(
[subfields_container] => Array
(
[textbox1] => <POSTed value>
)
)
All of the non-existent keys will just be created on the fly, regardless of the number of nested levels you specify.
Update
Given that the user can arbitrarily specify any number of nesting levels as elucidated below, you probably want a recursive function that returns the values for all the elements of the current level, and calls itself to retrieve the values for any elements at the current level that contain sub elements.
Example:
function getNestedPostVars($config, $formName, $keys = array()) {
$output = [];
foreach ($config as $label => $fieldConfig) {
if (isset($config['subfields'])) {
$output[$label] = getNestedPostVars(
$config['subfields'],
$formName,
array_merge($keys, array($label))
);
continue;
}
$output[$label] = /* path to $_POST element using $keys/$label */ ;
}
return $output;
}
i have a form with some checkboxes. if i activate a ceckbox, jquery is sending the data with the .serialize() function to a php file via ajax. The problem is, that jquery send some double parameters. Here is the Query:
area=26-50&area=51-75&area=76-100&area=100&std=1&std=3
How can i create a array like this:
array(
'area' => array(0 => '26-50',1 => '51-75',2 => '76-100'), std => array(0 => 1,1 => 3)
)
PHP overwrites the last variable with a new one...
Thanks for the help!
greetings
[] notation will make it possible to transmit array data in a form.
Name the checkboxes in the form like this:
<input name="area[]" type="checkbox" value="51-75">
this should build an array of all selected check boxes.
PHP can support this if the key name is appended with []:
area[]=26-50&area[]=51-75&area[]=76-100&area[]=100&std[]=1&std[]=3
/*
Array
(
[area] => Array
(
[0] => 26-50
[1] => 51-75
[2] => 76-100
[3] => 100
)
[std] => Array
(
[0] => 1
[1] => 3
)
)
*/