-1

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?

Lemon Kazi
  • 3,308
  • 2
  • 37
  • 67
Matte89
  • 3
  • 1

1 Answers1

0

Though it should be closed as a type, I will explain

foreach( $dynamic_form as $form ); {echo $form;} 

is executed as

foreach( $dynamic_form as $form ) {
    // do nothing
} 
// echoes last value assigned to `$form` in loop.
{echo $form;} 

And yes,

foreach( $dynamic_form as $form );

is absolutely valid code (though I don't know why you could need it unless it is a typo, as in question).

u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Modularity. All the looping constructs have basically the same structure, and they all allow an empty body. – Barmar Apr 24 '19 at 10:28
  • Yes, it was a typo ( a really dumb one ). But at least i learnt something new! Ty – Matte89 Apr 24 '19 at 10:29
  • If answer helps - you can __accept__ and optionally upvote it. It will help other users and also increase your reputation. – u_mulder Apr 24 '19 at 11:26