2

I have an HTML form. When the form is submitted, a jQuery code is executed to append an array of objects before data is sent to the server. Each object contains information retrieved outside the form.

<form method="post" id="formID" action="test.php" accept-charset="utf-8">
    <!-- form inputs -->
</form>
$('#formID').submit(function() {
    var form = $(this);     
    $('.file').each(function(index) {
        var filedata = {
            name: $(this).find('.name').text(), 
            ordernum: index, 
            size: $(this).find('.size').text()
        };
        form.append('<input type="hidden" name="filedata[]" value="' + filedata + '"/>');
    });
});

My goal would be to retrieve these information on server side. Unfortunately, when I output $_POST data, I only get a generic Object data.

echo '<pre>';
print_r($_POST['filedata']);
echo '</pre>';

/* output */
Array
(
    [0] => [object Object]
    [1] => [object Object]
)

Is there a way to send an array of objects when submitting a form to server without using AJAX requests?

1 Answer 1

2

You need to stringify the object you concatenate to the HTML:

form.append('<input type="hidden" name="filedata[]" value="' + JSON.stringify(filedata) + '"/>');

You then need to deserialize that value in your PHP:

foreach($_POST['filedata'] as $d => $data)
{
    $obj = json_decode($data);
    echo '<pre>';
    print_r($obj['name']);
    print_r($obj['ordernum']);
    print_r($obj['size']);
    echo '</pre>';
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer. Unfortunately I get the following error on server side: Warning: json_decode() expects parameter 1 to be string, array given in D:\xampp\htdocs\upload\controller\testController.php on line 22.
You need to loop through each value in the $_POST['filedata'] array. I updated my answer for you
Unfortunately, still doesn't work (I get a blank output). Maybe there's something wrong in $_POST['filedata']? When I output it I get Array ( [0] => { [1] => { )
The would be an issue, yes. What do you see in the console if you do the following in the JS console.log(JSON.stringify(filedata))?
Find it out. The inverted commas into stringified data was in conflict with those in append command. I've changed it to form.append("<input type='hidden' name='filedata[]' value='" + JSON.stringify(filedata) + "'/>");. And then to access members correctly also changed this on PHP: $obj = (array) json_decode($data);. Maybe consider to update the answer to fix those issues. Thanks for your help.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.