0

Hi I have a fair experience in javascript and I am stuck in the following situation.
I am developing a PHP page to display some values in a graph. I am using morris.js.

Now as morris.js uses array in following format to display as a graph:

// AREA CHART
            var area = new Morris.Area({
                element: 'revenue-chart',
                resize: true,
                data: [
                    {y: '2011', purchase: 500, sale: 1000, profit: 500},
                    {y: '2012', purchase: 600, sale: 1100, profit: 500},
                    {y: '2013', purchase: 500, sale: 1050, profit: 550}
                ],
                xkey: 'y',
                ykeys: ['profit', 'purchase', 'sale'],
                labels: ['Profit', 'Purchase', 'Sale'],
                lineColors: ['#a0d0e0', '#3c8dbc', '#ac5bc3'],
                hideHover: 'auto'
            });

But I have those values in php variable like:

$year1 = '2011';
$sale1 = '1000';
$purchase1 = '500';
$profit1 = '500';

$year2 = '2012';
$sale2 = '1200';
$purchase2 = '600';
$profit2 = '500';

$year3 = '2013';
$sale3 = '1050';
$purchase3 = '500';
$profit3 = '550';

How can I pass those php values to js. I tried json_encode() but it didn't work form me.

UPDATE: Displaying updated code with Luke Cordingley's answer, still have problem with it.

        <script type="text/javascript">
        window.MyProjectNamespace.phpVars = <?
                $phpVars = array('year' => '2011', 'purchase' => '1000', 'sale' => '600', 'profit' => '400');
                echo json_encode($phpVars);
                ?>
    </script>

    <script type="text/javascript">
        $(function() {

            // AREA CHART
            var area = new Morris.Area({
                element: 'revenue-chart',
                resize: true,
                data: [
                    {y: window.MyProjectNamespace.phpVars.year, purchase: "500", sale: "1000", profit: "500"},
                    {y: "2012", purchase: "600", sale: "1100", profit: "500"},
                    {y: "2013", purchase: "500", sale: "1050", profit: "550"}
                ],
                xkey: 'y',
                ykeys: ['profit', 'purchase', 'sale'],
                labels: ['Profit', 'Purchase', 'Sale'],
                lineColors: ['#a0d0e0', '#3c8dbc', '#000000'],
                hideHover: 'auto'
            });
    });
sohal07
  • 440
  • 8
  • 21

2 Answers2

2

You need to dynamically generate your javascript or as I prefer, create a JavaScript object that corresponds to my PHP variables. Once you get your PHP vars into JavaScript simply pass them to any JavaScript methods as needed. Here is an example of how to get your PHP variables in JavaScript:

<script type="text/javascript">
    $(function() {
         window.MyProjectNamespace = {};
         window.MyProjectNamespace.phpVars = <?php
            $phpVars = array('year' => '2011', 'purchase' => '1000', 'sale' => '600', 'profit' => '400');
            echo json_encode($phpVars);
            ?>;

        // AREA CHART
        var area = new Morris.Area({
            element: 'revenue-chart',
            resize: true,
            data: [
                {y: window.MyProjectNamespace.phpVars.year, purchase: "500", sale: "1000", profit: "500"},
                {y: "2012", purchase: "600", sale: "1100", profit: "500"},
                {y: "2013", purchase: "500", sale: "1050", profit: "550"}
            ],
            xkey: 'y',
            ykeys: ['profit', 'purchase', 'sale'],
            labels: ['Profit', 'Purchase', 'Sale'],
            lineColors: ['#a0d0e0', '#3c8dbc', '#000000'],
            hideHover: 'auto'
        });
    });
</script>
Luke Cordingley
  • 665
  • 4
  • 11
  • can u pls xplain where `console.log(window.MyProjectNamespace.phpVars);` is to be inserted. I tried replacing `data: [......]` in the code above with `data: [console.log(window.MyProjectNamespace.phpVars);]` but didn't work this way. – sohal07 Feb 20 '14 at 00:16
  • console.log is simply a debug function that shows you what is contained in a specific variable. For example if you have `json_encode(array('one' => 1, 'two' => 2));` in PHP that will create a JavaScript standard object like `{'one': 1, 'two': 2}`. So if you want to put all your PHP variables in to JavaScript, using my example you could access the value of variable 'one' as: `window.MyProjectNamespace.phpVars.one`. The value of that variable would be "1". You can pass the necessary variables to the Morris.Area method once they are in JavaScript as shown: – Luke Cordingley Feb 20 '14 at 01:58
  • Hi Luke, i have just updated my question with applying your answer, still have some problems with it. Pls hav a look. – sohal07 Feb 20 '14 at 04:49
  • "MyProjectNamespace" was just a placeholder for your project, you don't have to call it that. Can you be more specific with the problem you are having? – Luke Cordingley Feb 20 '14 at 17:01
  • ya i understand that...i just copied as it is to see if its gonna workk anyway... – sohal07 Feb 21 '14 at 01:41
  • Srry but i am still stuck there...pls hav a look at the updated code in my question and let me know where i am making mistake. – sohal07 Feb 21 '14 at 01:43
  • Okay, I updated my answer for you. First off you should just declare the new variable inside the ready doc, not necessary but in this case doesn't hurt. Secondly you have to declare the namespace as an object first so I apologize I should have been more specific. Third, you don't want to use PHP short tags ever. This is deprecated and you should always use `` instead of ` echo $foo ?>` or `= $foo ?>`. Lastly, I added a semicolon after the PHP processing to be on the safe side since it's good to end your JavaScript with a semi-colon. Hope that helps! – Luke Cordingley Feb 21 '14 at 05:14
  • thanks for your help. it is working now.....really appreciate your answer. – sohal07 Feb 22 '14 at 05:03
0

You should use ajax in your javascript to get variables from server side.

if you use jquery:

 $.ajax({
     type     : "POST",
     url      : "get_my_Variable.php",
     dataType: "json",
     data     : {hello:'i`m'},
     success : function(msg) {
         // here u get your variables
     },
     complete : function(r) {
     },
     error:    function(error) {
     }
 });

in server side:

 if(isset($_POST['hello'])){
    echo json_encode($myVariables);
 }
ZiupeX
  • 338
  • 3
  • 13