How to best populate calendar with events from database

Viewed 444

I'm creating a calendar from scratch and can't figure out how to populate it with birthday events from a database. I'm not sure how to work the event data into the loop that creates the calendar days or even if that is the correct order I should be doing it?

$.post('fetch-event.php', function(result){  
    let days = "";
    currentMonth = date.getMonth() +1;  

    // days of the current month and finds today's date
    for(let i = 1; i<=lastDay; i++){
        if(i === new Date().getDate() && date.getMonth() === new Date().getMonth()){
            days += `<div class="today" id="${i}/${currentMonth}/${year}">${i}</div>`;
        } else{
            days += `<div id="${i}/${currentMonth}/${year}">${i}</div>`;
        }
    }
    monthDays.innerHTML = days;
});

The 'result' of the post function produces the following.

[{"id":"1","name":"Elliot","date":"31/12/2020"},
 {"id":"2","name":"Phil","date":"17/1/2020"},
 {"id":"3","name":"Toby","date":"25/1/2021"}]

Ideally if the id date of the div matches the date from the database, I want to populate the div with the name of the person in the database rather than the day number but this is a bit beyond my technical know how.

1 Answers

You can use findIndex this will return index value of array if match found then using this indexvalue fetch name from your JSON Array i.e : result[index].name then add this to your divs .

Demo Code :

let days = "";
date = new Date();
currentMonth = date.getMonth() + 1;
year = date.getFullYear()
let monthDays = document.getElementById("monthDays")
var result = [{
    "id": "1",
    "name": "Elliot",
    "date": "31/1/2021"
  },
  {
    "id": "2",
    "name": "Phil",
    "date": "17/1/2021"
  },
  {
    "id": "3",
    "name": "Toby",
    "date": "25/1/2021"
  },
   {
    "id": "4",
    "name": "Abc",
    "date": "10/1/2021"
  }
]

// days of the current month and finds today's date
for (let i = 1; i <= 31; i++) {
  var dates = `${i}/${currentMonth}/${year}`
  //find index of date inside result array
  var index = result.findIndex(function(item, i) {
    return item.date === dates
  });
  var names = "";
  //if found
  if (index != -1) {
    names = result[index].name //get name at that index
  }
  //check if not "" display name or `i` value
     value = names != "" ? names : i ;
  if (i === new Date().getDate() && date.getMonth() === new Date().getMonth()) {
    days += `<div class="today" id="${i}/${currentMonth}/${year}">${value}</div>`;
  } else {
    days += `<div id="${i}/${currentMonth}/${year}">${value}</div>`;
  }
}
monthDays.innerHTML = days;
.today {
  color: red
}

#monthDays div {
  border: 1px solid black;
  width: 80px;
  height: 20px;
}
<div id="monthDays">
</div>

Related