0

I am trying to embed a data picker calendar in my php site. The code, which came off the shelf from DatePicker, allows to select some pre-highlighted dates, which is good as I have a list in a db table with the dates I need.

However, I have had no success in finding a way to include php within the script, or the other way round.

The original calendar script is as follows:

<script type='text/javascript'>

$(function() {
$("#txtDate").datepicker({dateFormat: 'yy-mm-dd'});
});

$(document).ready(function() {

    var SelectedDates = {};
    SelectedDates[new Date('02/24/2014')] = new Date('02/24/2014');
 SelectedDates[new Date('03/10/2014')] = new Date('03/10/2014');

    $('#txtDate').datepicker({
        beforeShowDay: function(date) {
            var Highlight = SelectedDates[date];
            if (Highlight) {
            return [true, "Highlighted", Highlight];
        }
        else {
            return [true, '', ''];
        }
    }
});
});
  </script>

I would like to be able to select a long list of dates to go in SelectedDates[new Date('03/10/2014')] = new Date('03/10/2014');

so my original idea was to do as follows:

$(document).ready(function() {
        var SelectedDates = {};

  <?php 
$query = "SELECT eventDate FROM database.calendar WHERE tag='R' AND competition='1'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
    $eventdate = $row[0];

SelectedDates[new Date('$eventdate')] = new Date('$eventdate');
}
?>

Sadly, this doesn't work (and neither do any of the various attempts to re-add tags within the PHP.

Any idea? Thank you so much for your help!

3

1 Answer 1

1

You have to close your PHP tags to output JavaScript (or use echo as mentioned in a comment):

$(document).ready(function() {
    var SelectedDates = {};

    <?php 
    $query = "SELECT eventDate FROM database.calendar WHERE tag='R' AND competition='1'";
    $result = mysql_query($query);
    while ($row = mysql_fetch_row($result)) {
        $eventdate = $row[0];
        ?>
        SelectedDates[new Date('<?php echo $eventdate; ?>')] = new Date('<?php echo $eventdate; ?>');
        <?php
    }
    ?>
});

Although I should mention that what you are trying to do is not really ideal. Do the PHP while loop separately, get that into an array, and json_encode that.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this - I shall try that right away. Still not overly familiar with arrays but they seem to be cropping up more and more - one for the lessons soon!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.