The website have a function to let member customized the form content, therefore I can't control a number of form fields, maybe they will submit over 1000 form fields to server, over the max_input_vars
limits, but the form fields should be unlimited, and I don't want to enlarge the number of max_input_vars
aimlessly, so I am trying to combine all fields and value into JSON string and decode it in PHP
FORM
<form id="frm" action="get.php" method="POST">
<input type="text" name="name" value="chan">
<input type="text" name="age" value="37">
<input type="text" name="hobby" value="basketball">
<button type="submit">go</button>
</form>
js
$(function() {
$('#frm').on('submit', function() {
var data = JSON.stringify($(this).serialize());
$.post('get.php', {data: data}, function(response) {
console.log(response);
});
return false;
});
});
PHP
<?php
$data = json_decode($_POST['data'], true);
var_dump($data);
I got "name=chan&age=37&hobby=basketball"
, I was thought I can use parse_str
to restore it, but parse_str
also effected by max_input_vars
, thefore I cange serialize()
to serializeArray()
, and I got
array(3) {
[0]=>
array(2) {
["name"]=>
string(4) "name"
["value"]=>
string(4) "chan"
}
[1]=>
array(2) {
["name"]=>
string(3) "age"
["value"]=>
string(2) "37"
}
[2]=>
array(2) {
["name"]=>
string(5) "hobby"
["value"]=>
string(10) "basketball"
}
}
I don't know how to correct it.
Use array (collection) of form fields! And of course, use POST method instead of GET because GET is more limited.
<form id="frm" action="action.php" method="POST">
<input type="text" name="myfields[name]" value="chan">
<input type="text" name="myfields[age]" value="37">
<input type="text" name="myfields[hobby]" value="basketball">
<button type="submit">go</button>
</form>
and then in your PHP code (action.php) fetch this array from $_POST and treat it as an array.
$myfields=$_POST['myfields']
foreach($myfields as $key=>$val)
{
echo $key.':'.$val.'<br>';
}
you'll get:
name:chan
age:37
hobby:basketball