Jump to content

Proper way to create JavaScript object using PHP


NotionCommotion

Recommended Posts

I've flip-flopped on this topic for a while.  I need some data available to the client which is generated using PHP.  Below are two options to do so.  Is one preferred over the other?  Is there a better option?  Thank you

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Generating Serverside Generated JavaScript Object</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
        <script>
            //Option 1: Generate the appropriate JavaScript directly using PHP
            var myJSONObj_1=<?php echo json_encode(array('a'=>1,'b'=>2,'c'=>3, 'd'=>array('x'=>1,'y'=>2,'z'=>3)));?>;
            $(function() {
                //Add all my JavaScript here...
                console.log('myJSONObj_1 test 1',myJSONObj_1);
            });
        </script>
        <script>
            $(function() {
                //Option 2: Server to just provide JSON
                $.getJSON( 'getMyJSON.php', function(myJSONObj_2) {
                    //Add all my JavaScript here...
                    console.log('myJSONObj_2 test 1',myJSONObj_2);
                });
            });
        </script>
        <script>
            //Some other imported script
            
            //No problem here
            console.log('myJSONObj_1 test 2',myJSONObj_1);
            
            //Opps, not so good, anything we could do?
            console.log('myJSONObj_2 test 2',myJSONObj_2);
            
        </script>
    </head>
    <body>
    </body>
</html>

getMyJSON.php

<?php
  header('Content-Type: application/json;');
  echo json_encode(array('a'=>1,'b'=>2,'c'=>3, 'd'=>array('x'=>1,'y'=>2,'z'=>3)));
?>

depends on the application you're building.

Retrieving the json via ajax will entail an extra connection from each client, though useful if this information will be updated regularly via polling.

 

Having the json in the original php script will use less resources and will ensure the data is available to your javascripts when the page loads... though as above if you're updating the results via ajax anyway you may want to just retrieve via ajax... which would be be most logical for your application?

which would be be most logical for your application?

 

Depends which part of my application :)  I have similar need multiple places.  Sounds like you recommend that if the data is static, directly output the data as a JavaScript object, right?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.