views:

39

answers:

5

Is it possible to take the contents of a variable and stick it into an array like so (I've tried to no avail):

First I get these values from a database and using php form into a hidden input:

{value: '1', name: 'name1'},{value: '2', name: 'name2'}

Then collect with javascript

document.getElementById("myelement").value

Then put the value

var meval = document.getElementById("myelement").value;

And then I try to build the data like so:

var data = {items: [meval]};

If I do this

var data = {items: [{value: '1', name: 'name1'},{value: '2', name: 'name2'}]};

it works but not the initial way with the variable. And I have to build the original data like that.

+1  A: 

You need to eval that variable to turn it's content into the data structure:

var data = {items: [eval(meval)]};
DVK
eval gives an unexpected token ":" error
play
+2  A: 

If your using a string, you can use eval() - but it's a bit naughty, as it introduces security & flow problems.

var meval = "[{value: '1', name: 'name1'},{value: '2', name: 'name2'}]";

var data = eval(meval);

Dave
+2  A: 

eval() is evil! Use JSON.parse() instead.

var data = {items: JSON.parse('['+meval+']')};

If you have jQuery included on your website, you can do $.parseJSON() which works better on older browsers.

Eric
I get an unexpected token: ILLEGAL error
play
@play: That's because your json is malformed. You should be outputting this from your database: `{"value": "1", "name": "name1"},{"value": "2", "name": "name2"}`. PHP's `json_encode()` will do that.
Eric
@play: Let me repeat myself: **That's because your json is malformed**. Once more: **YOUR JSON IS MALFORMED**. You should be outputting this from your database: `{"value": "1", "name": "name1"},{"value": "2", "name": "name2"}`.
Eric
I posted the comment before refreshing the page so I didn't see your comment. Thanks for your help. Sorry for the mix up. I tried now it gives me an "unexpected end of input" error
play
Then you forgot to close a bracket / quote
Eric
Thank you so very much. It was because of the echo some quotes were somehow being escaped.
play
Not all browsers support JSON.parse -Only: Mozilla Firefox 3.5+, Microsoft Internet Explorer 8, Opera 10.5+, Webkit-based browsers (e.g. Google Chrome, Apple Safari) http://en.wikipedia.org/wiki/Json#Native_JSON
Dave
Good point. `$.parseJSON()` works on all browsers though
Eric
A: 

Put the items into a hidden input in this format:

"name1"."|"."name2"."|"."name3"... and so on

Then in JS:

var list = document.getElementById("yourelement").value;
var arrayOfStuff = list.split("|");

Now your JS array looks like this:

array() {
    [0] => "Name1"
    [1] => "Name2"
    [2] => "Name3"
    ... and so on
}
Dai
+2  A: 

Eric is right, you're generally better off using JSON than arbitrary JavaScript literals. Currently your literal isn't valid JSON because it's not using double-quoted property names and string values. Use json_encode to get a JSON-compatible literal syntax.

You can fall back to eval() as in other answers when JSON.parse isn't available, but you will need to use extra brackets to ensure that eval knows that the leading { means an object literal and not a statement.

<?php
    function js($s) { // shortcut to save some typing
        echo json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS);
    }

    $data= array(name=>$row['name'], value=>$row['value']);
?>
<input type="hidden" id="data" value="<?php js($data); ?>"/>

<script type="text/javascript">
    var json= document.getElementById('data').value;
    var data= 'JSON' in window? JSON.parse(json) : eval('('+json+')');
</script>

Actually the JSON_HEX options in the js function allow literals to be output in a way that is equally valid in an HTML attribute or a <script> block, so you can indeed omit the hidden input and just say:

<script type="text/javascript">
    var data= <?php js($data); ?>;
</script>
bobince
Thanks for the input. I solved the problem. Somehow through the echo in php something was being escaped.
play