4

I have a question regarding data transmission from php to javascript. I gather some data from database and I format them like this:

for($i=0;$i<(sizeof($lt_periods_query['period_id']));$i++){

    $period_id   = $lt_periods_query['period_id'][$i];
    $lt_id       = $lt_periods_query['lt_id'][$i];
    $period_name = $lt_periods_query['period_name'][$i];
    $fDate       = $lt_periods_query['fromDate'][$i];
    $tDate       = $lt_periods_query['toDate'][$i];
    $minStay     = $lt_periods_query['min_stay'][$i];
    $nightly_rate= $lt_periods_query['nightly_rate'][$i];

    if (strStartsWith($fDate, $currentYear)=='true'){
        $year = $currentYear;
    } else if(strStartsWith($fDate, $nextYear)=='true'){
        $year = $nextYear;
    }

    $temp_period_details   =  array();
    $temp_period_details['period_id'] = $period_id;
    $temp_period_details['lt_id'] = $lt_id;
    $temp_period_details['period_name'] = $period_name;
    $temp_period_details['fromDate'] = $fDate;
    $temp_period_details['toDate'] = $tDate;
    $temp_period_details['min_stay'] = $minStay;
    $temp_period_details['nightly_rate'] = $nightly_rate;

    $periods[$year][$period_name] = $temp_period_details;
}

And I am able to see them when I print as like this:

echo "RULE for 6 days <br>";
$days= '5';
$selPeriod = 'off_peak';
$selYear = '2011';
echo $periods[$selYear][$selPeriod]['period_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['lt_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['period_name'];

I know that php is working on the server side and javascript is working on the client side. I want to get the data from javascript side by sending some parameters like this (I know why this is not working but I do not know how I can achieve such data transfers):

    <script type="text/javascript">

    $(function(){

        getData();

        function getData(){

            var days= '5';
            var selPeriod = 'off_peak';
            var selYear = '2011';


            //var xxx     = '<?php echo $periods[\''+selYear+'\'][\''+selPeriod+'\'][\'fromDate\'] ;?>';
            //var xxx = '<?php include($periods['2011']['off_peak'][''])?>;

        }

    });

Can anyone advice me a way to gather data from php to javascript by sending some parameters.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user403295
  • 818
  • 3
  • 15
  • 19

3 Answers3

19

To communicate data structures from PHP to Javascript, inject a JSON value like this:

<?php
     $xdata = array(
          'foo'    => 'bar',
          'baz' => array('green','blue')
     );
?>
<script type="text/javascript">
    var xdata = <?php echo json_encode($xdata); ?>;

    alert(xdata['foo']);
    alert(xdata['baz'][0]);

    // Dot notation can be used if key/name is simple:
    alert(xdata.foo);
    alert(xdata.baz[0]);
</script>

This can be used to properly escape scalars, arrays, objects, etc.

Kelstar
  • 810
  • 6
  • 15
  • 1
    This is the solution I used. The other code is worked as well. But I could not assign the array into a public variable. Thank you very much. – user403295 Nov 08 '10 at 06:02
  • Hi Hallman, I hope you see my message. I need some help related with the same problem I had yesterday. Can you please tell me what kind of variable is this 'xdata'? It looks a public variable but I am not able to call and use it from other methods. Some of them let but some does not let me to call it. I have got a calendar. On mouseover event, I call this array. and it does not pull variables out of it. What the reason could be and how can I solve it. Thanks in advance. Ozlem. – user403295 Nov 09 '10 at 00:39
1

Simple AJAX approach.

Put all your data into single array. Then use json_encode to encode your data to JSON format.

$data_array = array();

//assigning your data to single array here
$data_array['param1'] = 'value1';

echo json_encode($data_array);

Then in your JavaScript code use AJAX to call you script. For example use great jQuery library for this (http://api.jquery.com/jQuery.getJSON/).

<script type="text/javascript">    

$.getJSON('http://www.example.com/my_script.php', function(data) {
    alert(data.param1); //this should alert 'value1'
});
Daimon
  • 3,703
  • 2
  • 28
  • 30
  • I got sth like this converting the the array into json object..I hope you can see it clearly.. As you will see first variables are number and I need to pull relevant year data according to users selection. Can you please help me how I can get the data from this array dynamically.. For example year:2011 season:peak (assume that year and season are variable that I will use.) – user403295 Nov 07 '10 at 23:26
  • This is the data I could not put it in he previous comment.(I have shortened the data) {"2010":{"peak":{"period_id":"8","lt_id":"1","period_name":"peak","fromDate":"2010-01-30","toDate":"2010-05-01","min_stay":"2","nightly_rate":"407.14"}, "off_peak":{"period_id":"9","lt_id":"1","period_name":"off_peak","fromDate":"2010-05-01","toDate":"2010-09-19","min_stay":"2","nightly_rate":"300.00"}, "2011":{"peak":{"period_id":"4","lt_id":"1","period_name":"peak","fromDate":"2011-01-30","toDate":"2011-05-01","min_stay":"2","nightly_rate":"407.14"}} – user403295 Nov 07 '10 at 23:31
  • You can access JSON data in javascript using object-like and array-like way (read more here: http://www.json.org/js.html). Process your array in PHP to suite your array access needs. – Daimon Nov 07 '10 at 23:53
1

There's the AJAX method, and there's the echoing method. The former is more flexible, while the latter is a lot simpler and doesn't require you to cope with AJAX errors.

For the former, there are plenty of examples around the place on how to use AJAX. The latter can be achieved quite simply:

<script type="text/javascript">
var phpVar = <?php echo ($phpVar); ?>;
</script>

Which approach is approporite depends on what data your javascript needs and what it needs it for. If you're needing to do a lot of server interaction, then working with AJAX is the avenue you should be investigating. However, if all you need is an initial value to initialize a javascript, then the latter approach is a lot easier to implement.

GordonM
  • 31,179
  • 15
  • 87
  • 129