So, I'm appending an array of objects to a FormData
and sending the form with an ajax
post request.
On my php page, I can access all form elements just fine (with the usual $_POST['field_name']
), but when I try to access the array element I have appended, I'm having some problems.
Basically if I var_dump
the element (called $_POST['dynamic_form']
) I see an array of 2 (which is correct), but if I try to loop this array and echo the values only the last element of the array is echoed.
for (var i = 0; i < form_elements.length; i++) {
formData.append('dynamic_form[]', JSON.stringify(form_elements[i])); }
//THIS IS MY AJAX REQUEST
$.ajax({
type: 'POST',
url:'myurl',
data:formData,
processData: false,
contentType:false,
success: function(msg){
console.log(msg);
alert("form saved");
},
error: function(){
alert("request failed");
} });//fine ajax
//HERE MY PHP $dynamic_form = $_POST['dynamic_form']; var_dump($dynamic_form);
foreach( $dynamic_form as $form ); {echo $form;}
the var_dump
result in the console is correct:
array(2) { [0]=> string(59) "{"type":"text","name":"","value":"2","label":"disponibile"}" [1]=> string(55) "{"type":"textarea","name":"","value":"1","label":"asd"}" }
but the echo
inside the foreach
loop only shows the last element of the array:
{"type":"textarea","name":"","value":"1","label":"asd"}
is_array($dynamic_form)
returns true (correct)
count($dynamic_form)
returns 2 (correct)
I have tried a for
loop instead of the foreach
but I still have problems.. what am I doing wrong?