I am working on a site, and I am having to create a PHP loop with Javascript in it. Is this possible? Here is the snippet of code I need looped.
<? while($calendar = mysqli_fetch_array($client_get_calendar)) { ?>
{
title: '<? echo $calendar['event_title'] ?>',
start: new Date(<? echo date("Y", strtotime($calendar['date_start'])) ?>, <? echo date("m", strtotime($calendar['date_start'])) ?>, <? echo date("d", strtotime($calendar['date_start'])) ?>),
end: new Date(<? echo date("Y", strtotime($calendar['date_end'])) ?>, <? echo date("m", strtotime($calendar['date_end'])) ?>, <? echo date("d", strtotime($calendar['date_end'])) ?>),
className: '<? echo $calendar['importance'] ?>'
},
<? } ?>
Will this work for what I am trying to accomplish? It gives me an error, but I don't know what is wrong with the code. Thanks for any help!
You appear to be building JSON output for a Javascript object of data.
This would be better achieved with the following.
<?php
$calendar = mysqli_fetch_array($client_get_calendar);
echo json_encode($calendar);
?>
Modify the array as you like in a loop.
JSON
is good, JSON
don't kill Arctic Bears. Everytime someone build a Javascript object without JSON an Arctic Bear dies.
$rows = array();
while($calendar = mysqli_fetch_array($client_get_calendar)) {
$nRow = array(
'title' => '' /* <= do your tricks here */,
'start' => '' /* <= and here */,
'end' => '' /* <= and here */,
'className' => '' /* <= and here */
);
// Now append it do rows
$rows[] = $nRow;
}
// dat magic
echo json_encode($rows);
I assume you get a syntax error at IE.
And you are trying to make a javascript array of object.
In this case, you got an extra comma at the end of the script and that will cause error on IE. the solution is just like @IAmNotProcrastinating said, make a json.
so as the answer above, you can save your data and encode it into a json string.
Continue @IAmNotProcrastinating work, instead of direct output:
<?php
if(count($row)>0){
$data = json_encode($row);
}
else{
$data = json_encode(array());
}
?>
var js_data = <?php echo $data; ?>;
do_something_with_js_data(js_data);