0

I'm setting an array to a hidden field using JavaScript. However, the issue is that the array gets converted to a string on form submit when I catch it using PHP.

This is the code that sets the hidden input field value:

document.getElementById("hiddenFieldId").value = arrayFromJS;

Is there any workaround for this?

Actually the problem is earlier I had a select box which sent it's values nicely on form submit. But now I've got a custom select box using JS which sets comma separated values in a hidden field... So in a nutshell I want that input field to act like a pseudo-select box

3
  • 1
    json (encode and decode) Commented Aug 14, 2013 at 13:07
  • 1
    More code is needed. What is the array you are setting? How are you submitting the form? Commented Aug 14, 2013 at 13:07
  • I'd prefer that nothing changes at the server end. I'm submitting the form using POST Commented Aug 14, 2013 at 13:52

1 Answer 1

1

You should JSON encode/decode the value:

On the client side you use JSON.stringify to encode the array:

document.getElementById("hiddenFieldId").value = JSON.stringify(arrayFromJS);

And then on the server side you can use json_decode:

$arr = json_decode($_POST['hiddenFieldId']); // Fetch the data from POST / GET

foreach ( $arr as $value ) {
    // iterate the array on the server side.
}

unset($arr); // Remember to unset the $arr variable

If you know you are handeling a simple array (with string only) you can join the string in javascript and explode/split it php:

document.getElementById("hiddenFieldId").value = arrayFromJS.join('/:/');

PHP:

$arr = explode('/:/', $_POST['hiddenFieldId']);

To support older browser you can use this JSON plugin to the front end: https://github.com/douglascrockford/JSON-js

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

Comments

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.