Reputation: 49
I have form something like that:
<form id="incomes" method="post" action="#">
<input type="text" name="date[]"/>
<input type="text" name="income[]"/>
<input type="text" name="tax[]"/>
<input type="text" name="social_insurance[]"/>
<input type="text" name="health_insurance[]"/>
</form>
All I want to do is to post that inputs via jQuery ajax to php in structure like this:
Array(
[0] => Array(
date => 2012-12-10
income => 1000
tax => 100
social_insurance => 50
health_insurance => 50
)
[1] Array(
date => 2012-12-15
income => 2000
tax => 150
social_insurance => 20
health_insurance => 50
)
)
Is there any simple way to achieve that? I've heard about serialize() function but that isn't what I want to...
Upvotes: 0
Views: 739
Reputation: 171689
sending the form data using jQuery serialize()
is simplest way to send the data. You would need to loop over the individual field arrays in php to create the array structure you want
$('#incomes').submit(function(){
$.post(url, $(this).seralize(), function(response){
/*run any ajax complete code here*/
}) ;
/* prevent browser default form submit*/
return false;
});
$_POST will look like:
array(
date=> array(),
income=>array()/* etc*/
}
PHP new array Loop could look something like:
$newArray=array();
foreach($_POST as $key=>$value){
if( !empty( $value) && is_array($value)){
for( $i=0;$i<count($value);$i++){
$newArray[$i][$key]=$value[$i];
}
}
}
Upvotes: 0
Reputation: 2869
I do it myself all the time but I do it on the PHP side looping through an array:
$newarray = array();
foreach($_POST["date"] AS $i => $date) {
$newarray[$i]["date"] = $date;
}
and so on..
So you keep sending your data via ajax as it is and do everything on server side, there you can sort and do whatever you need to the array before processing and outputting the result
Upvotes: 1