Reputation: 484
I have the following code that will output a line chart as follows :
<script class="code" type="text/javascript">
$(document).ready(function(){
var line1=[['2008-08-12 ',14], ['2008-09-12 ',6.5], ['2008-10-12 ',5.7], ['2008-11-12 ',9], ['2008-12-12 ',8.2]];
var plot1 = $.jqplot('chart1', [line1], {
title:'Daily Sales',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer
}
},
series:[{lineWidth:4, markerOptions:{style:'square'}}]
});
});
</script>
The output for the above code is correct, but i want to insert a PHP loop to select data from mysql and place it insde var line1
as an array
So I created a test code as follows :
<script class="code" type="text/javascript">
$(document).ready(function(){
<?php
$date = date('Y-m-d');
for($i=1;$i<6;$i++){
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
?>
var line1=[['<?php echo $newdate; ?> ',<?php echo $i ?>]];
<?php
$date = $newdate;
}
?>
var plot1 = $.jqplot('chart1', [line1], {
title:'Daily Sales',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer
}
},
series:[{lineWidth:4, markerOptions:{style:'square'}}]
});
});
</script>
This outputs the last value which is 2015-5-16 and 5 all i want is to output all the result from 1 to 5 and having dates incremented by each month 2014-12-16 to 2015-5-16.
I hope this makes sense ! Thank You
Upvotes: 0
Views: 50
Reputation: 2698
Replace your PHP-Block for "var line1=[['..." with this:
<?php
$date = date('Y-m-d');
$js = " var line1=[";
for($i=1;$i<6;$i++) {
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
$newdate = date ( 'Y-m-j' , $newdate );
if($i>1) { $js.= ", "; }
$js.= "['".$newdate." ',".$i."]";
$date = $newdate;
}
$js.= "];";
echo $js;
?>
Upvotes: 0
Reputation: 360682
You're doing this wrong. You don't use PHP to dump text into a Javascript code block directly. That's a sure-fire way of introducing a javascsript syntax error and killing the entire code block.
You build a native PHP structure (array, object, whatever) and then you json_encode() that.
e.g.
<?php
$results = get_data_from_db();
$data = array();
while($row = fetch_row_from_result($results)) {
$data[] = array($row['foo'], $row['bar']);
}
?>
<script type="text/javascript">
var data_from_db = <?php echo json_encode($data); ?>;
</script>
Upvotes: 4