I have a td with a class name of "seminar_date_time" that I'm trying to set the inner html of after converting a datetime into a string format that I want. Here's my code...
if($stmt->execute()) {
$stmt->bind_result($id, $seminar_date, $am_pm, $room, $building, $speaker_lname, $speaker_fname, $title);
while($stmt->fetch()) {
?>
<script>
var date_object = new Date("<?php echo $seminar_date; ?>");
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var month = monthNames[date_object.getMonth()];
var day = date_object.getDay();
var year = date_object.getFullYear();
var hour = date_object.getHours();
var mins = date_object.getMinutes();
var time_string = null;
var ampm = null;
if(hour > 12) {
hour -= 12;
ampm = "PM";
}
else {
ampm = "AM";
}
if(mins === 0) {
mins = "00";
}
time_string = `${hour}:${mins} ${ampm}`;
// using ES6 string template literal for date string
var date_string = `${month} ${day}, ${year} at ${time_string}`;
console.log(`date and time: ${date_string}`);
$(".seminar_date_time").html(date_string);
</script>
<tr class="clickable_row" data-href="seminar_attendance.php?id=<?php echo $id; ?>">
<td class="seminar_date_time"></td>
<td><?php echo $room; ?></td>
<td><?php echo $building; ?></td>
<td><?php echo "$speaker_lname, $speaker_fname"; ?></td>
<td><?php echo $title; ?></td>
</tr>
<?php
}
}
When I render this to the page the date string in that td is the same for every row. When I console.log() my newly formed date string, it logs it perfect every time. The next line after that console.log() is setting the html via jQuery on the td with class name "seminar_date_time".
I know the php code is being set server side, so I'm guessing there's a racing problem between setting the server side content and setting the jQuery client side?
How can I get my new date string into each row's td correctly?
EDIT:
It sounds like the consensus here is that I need to be formatting the date in PHP instead of doing it through JS. That is what I plan to do now, but maybe these answers could still help someone else that needs to mix PHP and JS in this way. Thank you to all that answered.