1

I have an php made array:

<?php information = array (
    'name' => 'John',
    'surname' => 'Doe'
); ?>

I serialize this array with php and put it into input's value:

<input type="hidden" id="information" name="information" value="<?php echo htmlentities(serialize($hidden_information)); ?>" />

Now JS part. I get this input's value:

var information = $('input#information').val();

And the question part: how can I now unserialize with JS this PHP serialized array? I want to unserialize 'information' variable.
When it will be unserialized, I want to alert name and surname from array.

Or probably, is there any possible way to get this name and surname without unserializing the array?

3
  • You should only serialize if you are comunicating with PHP, if you want to have the name and surname of the person, just create 2 input fields with this info, if this is what you want I can create you an answer. Commented May 25, 2014 at 15:55
  • It will also communicate with PHP later for some other necessities. That's why I need to serialize it. Commented May 25, 2014 at 15:57
  • Use a format that both understand like JSON. Commented May 25, 2014 at 16:01

1 Answer 1

2

You'll need to transform the array to JSON format, it will be easier for JS to understand, so do this in your html:

<input type="hidden" id="information" name="information" value="<?php echo htmlentities(serialize($hidden_information)); ?>" //This will comunicate with PHP
<input type="hidden" id="js_information" name="js_information" value="<?php echo json_encode($hidden_information); ?>" />

The information input will be use to comunicate with PHP and js_information for comunicating with JS. Then you can get that info in JS using:

var information = JSON.parse($('#js_information').val());

Note: You'll need to have PHP 5.2 or superior, also there's no need to put input in the jQuery selector because you have the ID specified `

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

1 Comment

You still need to encode HTML’s special characters.

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.