7

I have a field on my page, like this:

<input type="hidden" name="myField" id="myField" />

and I have a piece of code that looks like this:

$(document).ready(function() {
    var myObject = {
        item1: 'item1 value',
        item2: 'item2 value',
        item3: 'item3 value',
        item4: 'item4 value',
    };

    $('#myField').val(myObject);
});

And when I submit this form, I catch and ouput the $_POST variable with print_r/var_dump functions and I get the following output for this Form Field (myField).

[myField] => [object Object]

How can I throw an JavaScript array/object to a form field and to have it evaluated/converted to a propper data-type on the server-side, so I could get it like this in my PHP script:

[myField] => Array(
    item1 => item1 value
    item2 => item2 value
    item3 => item3 value
    item4 => item4 value
)

How to achive this, without hard coding?

1 Answer 1

16

Encode the object as JSON [Wikipedia]:

$('#myField').val(JSON.stringify(myObject));

and decode it at the server side with json_decode [docs].

The JSON [docs] object is available in recent browsers and can also be included as library.

Sign up to request clarification or add additional context in comments.

1 Comment

For python users - the decoding function on the server side would be json.loads()

Your Answer

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