Reputation: 3582
I am pulling an array from a mysql database. A pretty simple select
statement that then gets put into your run-of-the-mill multi-dimension array (rows and columns) to generate some HTML. So far so good.
I want to be able to store that array somewhere (DOM?) on the client-side so that clients can re-use and manipulate that data (via jQuery) without having to re-query the database for the same data each time.
So... lets say my php array is:
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);
How do I store $fruits
on the client-side so I can re-use the data on command via javascript?
Upvotes: 1
Views: 4928
Reputation:
Actually, there is an issue with this and being "unsafe" (but I leave this reply for reference as well as exposing the flaw I didn't consider earlier):
If '</script>' appears in the output of the JSON (which is perfectly legal) then the HTML is invalid.
EDIT: json_encode
takes the optional JSON_HEX_TAG
which will prevent the above situation from occurring. Be sure to use the correct output escapes as required for context.
(And previous stuff...)
I am going to prose the same answer as everyone else...
...use json_encode
or a similar/better JSON encoding mechanism. This should result in the JSON -- JSON is a text representation of a subset of JavaScript object literals. This JSON is then (unless json_encode is broken) guaranteed to be a 100% valid side-effect-free expression in JavaScript.
...with one exception: just use the-valid-JS-expression as-is.
# Look, no added nonsense.
var blah = <?= json_encode($my_arr); ?>;
It is very unlikely that the JSON will have to be shoved into an element property before use with a good design. (E.g. likely no need for any "parsing" from a stored value; utilize JavaScript and the execution order between the back-end and front-end in emitting code.)
Please take the time to think about the different stages the processing occurs in. For instance, the following is wrong:
var blah = ParseJson("<?= json_encode($my_arr); ?>;")
It is wrong because after PHP is run the resultant HTML returned to the browser may be:
var blah = ParseJson("{"hello": "world"}")
Happy coding
Upvotes: 0
Reputation: 44444
How about storing it as a simple javascript object? Something like the folllowing:
//yourphpfile.php
<script type="text/javascript">
var obj = JSON.parse('<?php echo json_encode($my_arr,JSON_HEX_TAG|JSON_HEX_APOS); ?>');
console.log(obj);
</script>
The client side will have the entire data into the obj
object.
Upvotes: 4
Reputation: 19560
Serialize $fruits into JSON with json_encode, then write it to something like a hidden input. Using jQuery you can query the DOM for the input and $.parseJSON its value.
Server side:
<input type="hidden" id="FruitData" value="<?php echo htmlentities( json_encode( $fruits ) );?>" />
Client side:
var fruits = $.parseJSON( $( '#FruitData' ).val() );
You could put it anywhere you like, really--I just prefer an input. Inputs are handy for shipping the data back to the server too (via methods other than AJAX, even). Cookies would work too. I do avoid outputting directly into a script block though. I don't like how my syntax editor freaks out on PHP inside the JS, it often leads to a lot of globalized code, and it gets in my way when it comes time to move the script to an external file.
Also, as long as you're providing the JSON API to older browsers, you could replace $.parseJSON
with JSON.parse
.
Upvotes: 5
Reputation: 65952
One approach, and one that we (our company) has used before, is to echo that data as JSON in a hidden div
on the page. Then use a combination of jQuery's .text()
method and JSON.parse()
to get the data as JSON on the client side.
Something like this:
echo "<div id = 'fruits' style = 'display:none;'>".json_encode($fruits)."</div>";
Then in Javascript:
var fruits = JSON.parse($("#fruits").text());
console.log(fruits.fruits.a); // orange
Upvotes: 1