Skip to content Skip to sidebar Skip to footer

Best Way To Pass Data From Php To Javascript For My Particular Case

I've built an online community in Drupal with a homepage that is kind of like the Facebook wall. You see the 25 most recent posts, with the two most recent comments below those pos

Solution 1:

I've never heard of a standard way to "pass" information between PHP and Javascript, as they are a server-side and client-side language, respectively. I would personally use a hybrid of your second and third solutions.

Store the post id in a data-postindex attribute (data attributes are newish, and the "right" way to store small amounts of data). But I would still just use a JSON array for the rest, as storing lots of data in data-attributes (and escaping them!) is potentially problematic. PHP has a json_encode function that takes care of all the escaping and such for you - just build a PHP array (say, $postdata) like you normally would, and then throw this in your post template:

<scripttype="text/javascript">
    globalPostArray.push(<?phpecho json_encode($postdata) ?>);
</script>

Where $postdata is something like the following:

$postdata = array(
    'nid' => 5,
    'authorId' => 45
    ...etc...
);

It should be easy enough to generate such an array from your existing code.

I wrote a blog post a while back about my implementation of this kind of thing, but it sounds like all you need is a pointer at json_encode.

Solution 2:

The most reliable way to pass any PHP variable to JavaScript is json_encode.

<scripttype="text/javascript">var something = <?phpecho json_encode($var); ?>;
</script>

You can't pass closures and resources, but otherwise anything's game for being passed.

Solution 3:

I would store the data inside the element:

<divclass="post"data-postindex="<?phpecho$post->index; ?>"data-nid="<?phpecho$post->nid; ?>"data-authorID="<?phpecho$post->authorID; ?>">

...or storing a complete JSON-string in 1 data-attribute:

<divdata-data="<?phpecho htmlentities(json_encode($somedata));?>">

Solution 4:

My answer is about the same as the other guys but more detailed. I usually do it like this and i think is the best approach: (of course you can grab the data using ajax, but depends on the context)

somefile.html

<html><head>..</head><body>
        html code
        <script>window.my_data = <?phpecho json_encode($my_php_var); ?></script></body></html>

somefile.js

       $(function() {
          window.myitem = newmyClass(window.my_data);
       });
       varMyClass = function(init_data) {...}

Post a Comment for "Best Way To Pass Data From Php To Javascript For My Particular Case"