Jump to content

How do I highlight mysql fetch dates in a datepicker?


Go to solution Solved by imgrooot,

Recommended Posts

I am trying to create a simple calendar where a user can add/remove their availability date. This part works so far. Now what I am having trouble with is highlighting the already selected dates that are fetched from a MySQL database.

 

Here's my code.

// HTML
<div id="datetimepicker1"></div>
// Jquery/Ajax

<script>
$(document).ready(function () {

  $('#datetimepicker1').datepicker({
    dateFormat: "yy-mm-dd",
    multidate: true,
    onSelect: function () {
        var getDate = $("#datetimepicker1").val();

        $.ajax({
             type: "POST", //or GET. Whichever floats your boat.
             url: "snippets/adapter-set.php",
             data: { date: getDate },
             success: function(data) {
              // alert(data);
             },
             error: function() {
                 alert("Error.");
             }
        });
    }
  });
});
</script>
// PHP
// adapter-set.php

$post_date = $_POST['date'];

$find_query = $db->prepare("SELECT user_id FROM user_dates WHERE date_available = :date_available");
$find_query->bindParam(':date_available', $post_date);
$find_query->execute();
$result_find = $find_query->fetchAll(PDO::FETCH_ASSOC);
if(count($result_find) > 0) {
  foreach($result_find as $row) {
    $user_id =	$row['user_id'];
  }
  $delete_query = $db->prepare("DELETE FROM user_dates WHERE user_id = :user_id");
  $delete_query->bindParam(':user_id', $user_id);
  $delete_query->execute();
  $result_delete = $delete_query->execute();
  if($result_delete == false) {
   echo 'delete false';
  } else {
   echo 'delete success';
  }
} else {
  $insert_query = $db->prepare("INSERT INTO user_dates(date_available) VALUES(:date_available)");
  $insert_query->bindParam(':date_available', $post_date);
  $result_insert = $insert_query->execute();
  if($result_insert == false) {
   echo 'insert false';
  } else {
   echo 'insert success';
  }

}

 

The above code works fine. It inserts and deletes a date row in MySQL database table based on a click.

Now what I would like to do is to highlight all the "available" dates that are already inserted into the database; so that the user knows which dates he has already selected. This is my code for that. But it doesn't seem to be working. No errors. It's just not highlighting the inserted dates. Can you tell me what I'm doing wrong?

// JQUERY
<script>
    $(document).ready(function() {

        $.post('snippets/adapter-fetch.php', {}, function(data){
            $("#datetimepicker1").datepicker({
              datesEnabled : data.datesEnabled
            });
        }, 'json');

    });
</script>
// PHP
// adapter-fetch.php

$global_user_id = 5;

$find_query = $db->prepare("SELECT date_available FROM user_dates WHERE user_id = :user_id");
$find_query->bindParam(':user_id', $global_user_id);
$find_query->execute();
$result_find = $find_query->fetchAll(PDO::FETCH_ASSOC);
if(count($result_find) > 0) {
  foreach($result_find as $row) {
    $date_available =	$row['date_available'];

    echo $date_available;
  }
} else {
  echo 'not dates available';
}

 

1 hour ago, requinix said:

Have you looked at what output adapter-fetch.php is returning?

I used alert to return the output but it's not working. I might be doing it wrong. No popup shows up.

$.post('snippets/adapter-fetch.php', {}, function(data){
            $("#datetimepicker1").datepicker({
              datesEnabled : data.datesEnabled
              alert(data);
            });
        }, 'json');

It gives me this error.

Uncaught SyntaxError: Unexpected identifier

 

Edited by imgrooot
30 minutes ago, requinix said:

Definitely not the correct syntax.

You familiar with Javascript much? May be worth spending an hour or two learning about it.

Alright so I fixed that issue. The alert wouldn't work if I had the "json" in the function. Here's the updated code.

$.post('snippets/adapter-fetch.php', {},
function(data) {
  $("#datetimepicker1").datepicker({
    datesEnabled : data.datesEnabled
  });
  alert(data);
});

It returns the correct dates(eg. yy-mm-dd) from the adapter-fetch.php. Now I need to know how I can highlight these dates on the datepicker?

Edited by imgrooot
6 minutes ago, requinix said:

Exactly what did the alert show? Or change your alert to a console.log and copy/paste what you get in the console.

The alert shows the dates that the user already inserted into the database. Same output when using console.log.

Like this.  Shows three different dates without any spacing between them.

2021-06-022021-06-032021-06-01

 

Edited by imgrooot

I don't know what you think, but that is not a date. That's a bunch of numbers and hyphens.

Would you expect this

$.post('snippets/adapter-fetch.php', {},
function(data) {
  $("#datetimepicker1").datepicker({
    datesEnabled : "2021-06-022021-06-032021-06-01"
  });
});

to work?

Keep thinking in that direction for a few minutes and see what you can come up with.

On 6/28/2021 at 7:53 PM, requinix said:

I don't know what you think, but that is not a date. That's a bunch of numbers and hyphens.

Would you expect this


$.post('snippets/adapter-fetch.php', {},
function(data) {
  $("#datetimepicker1").datepicker({
    datesEnabled : "2021-06-022021-06-032021-06-01"
  });
});

to work?

Keep thinking in that direction for a few minutes and see what you can come up with.

I have finally solved this issue. It was a lot more complicated than I originally imagined. Here's code.

<script>
$(document).ready(function() {

  function formattedDate(d = new Date) {
    let month = String(d.getMonth() + 1);
    let day = String(d.getDate());
    const year = String(d.getFullYear());

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return `${year}-${month}-${day}`;
  }

  $.ajax({
    type: "POST",
    url: 'snippets/adapter-fetch.php',
    data: {},
    dataType: 'json',
    success: function(highlighted) {
      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,
        beforeShowDay: function(date) {
          newDate = formattedDate(date);
          for(let x=0; x < highlighted.length; x++) {
            if (highlighted[x] === newDate) {
              return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
            }
          }
          return [true, '']; // default if not a highlight
        }
      });
    }
  });
  
});
</script>
// PHP adapter-fetch.php

$global_user_id = 5;

$find_query = $db->prepare("SELECT date_available FROM user_dates WHERE user_id = :user_id");
$find_query->bindParam(':user_id', $global_user_id);
$find_query->execute();
$result_find = $find_query->fetchAll(PDO::FETCH_ASSOC);

$dates = [];

if(count($result_find) > 0) {
  foreach($result_find as $row) $dates[] = $row['date_available'];
}
echo json_encode($dates);

 

So now the above code will highlight all the dates I fetch from the database table. And my original code will insert and delete dates entries when clicking a date on the Calendar. 

Having said that I have a new issue. Here's the full code combined.

<script>
$(document).ready(function() {

  function formattedDate(d = new Date) {
    let month = String(d.getMonth() + 1);
    let day = String(d.getDate());
    const year = String(d.getFullYear());

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return `${year}-${month}-${day}`;
  }
  // THIS CODE WILL HIGHLIGHT THE DATES
  $.ajax({
    type: "POST",
    url: 'snippets/adapter-fetch.php',
    data: {},
    dataType: 'json',
    success: function(highlighted) {
      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,
        beforeShowDay: function(date) {
          newDate = formattedDate(date);
          for(let x=0; x < highlighted.length; x++) {
            if (highlighted[x] === newDate) {
              return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
            }
          }
          return [true, '']; // default if not a highlight
        }
      });
    }
  });

  // THIS CODE WILL INSERT/DELETE THE DATES
  $('#datetimepicker1').datepicker({
    dateFormat: "yy-mm-dd",
    multidate: true,
    onSelect: function () {
      var getDate = $("#datetimepicker1").val();

      $.ajax({
           type: "POST", //or GET. Whichever floats your boat.
           url: "snippets/adapter-set.php",
           data: { date: getDate },
           success: function(data) {
            // alert(data);
           },
           error: function() {
               alert("Error.");
           }
      });
    }
  });

});
</script>

It seems like the ajax code that highlights the dates won't work if I have both of them together. Can you tell me why I can't use the "$('#datetimepicker1').datepicker" twice in the same script? It doesn't return any errors. It just doesn't highlight the dates.

The date picker only allows one of itself to exist on #datetimepicker1 at a time. Imagine the types of conflicts there could be if it tried to run twice on the same control.

Your first datepicker code needs "highlighted" to know which dates to highlight. Instead of using the variable that comes from $.ajax, use a separate variable, and have the AJAX set that variable. For a brief moment after the page loads, the date picker will be set up and not highlighting any dates, but the user probably won't be able to hit the date picker fast enough to see that being the case.

With the datepicker initialization happening outside of the AJAX, you can more easily combine the beforeShowDay and onSelect options into that configuration object datepicker needs.

36 minutes ago, requinix said:

The date picker only allows one of itself to exist on #datetimepicker1 at a time. Imagine the types of conflicts there could be if it tried to run twice on the same control.

Your first datepicker code needs "highlighted" to know which dates to highlight. Instead of using the variable that comes from $.ajax, use a separate variable, and have the AJAX set that variable. For a brief moment after the page loads, the date picker will be set up and not highlighting any dates, but the user probably won't be able to hit the date picker fast enough to see that being the case.

With the datepicker initialization happening outside of the AJAX, you can more easily combine the beforeShowDay and onSelect options into that configuration object datepicker needs.

I sort of understand what you're trying to say. Can you show me an example of setting up a variable outside the ajax using my code? Seeing it would help a lot.  

23 hours ago, requinix said:
var highlighted = null;
$.ajax({
	...
	onSuccess: function(data) {
		highlighted = data;
	}
	...
});

 

Been trying your method many different ways and it still doesn't work. 

Could you please add your edits to the entire code below instead of bits and pieces? Here's my code with your supposed update code. It doesn't return any errors, but it doesn't highlight the dates either.

<script>
$(document).ready(function() {

  function formattedDate(d = new Date) {
    let month = String(d.getMonth() + 1);
    let day = String(d.getDate());
    const year = String(d.getFullYear());

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return `${year}-${month}-${day}`;
  }
  //CODE#1
  // THIS CODE FETCHES DATES FROM A MYSQL TABLE AND HIGHLIGHTS THEM ON A DATEPICKER CALENDAR

  var highlighted = null;

  $.ajax({
    type: "POST",
    url: 'snippets/adapter-fetch.php',
    data: {},
    dataType: 'json',
    success: function(data) {

      highlighted = data;

      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,

        beforeShowDay: function(date) {

          newDate = formattedDate(date);

          for(let x=0; x < highlighted.length; x++) {
            console.log(highlighted[x], newDate);

            if (highlighted[x] === newDate) {
              return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
            }
          }
          return [true, '']; // default if not a highlight
        }

      });
    }
  });

  // CODE#1
  // THIS CODE INSERTS AND REMOVES THE SELECTED DATES FROM THE MYSQL TABLE.
  $('#datetimepicker1').datepicker({
    dateFormat: "yy-mm-dd",
    multidate: true,
    onSelect: function () {
        var getDate = $("#datetimepicker1").val();

        $.ajax({
             type: "POST",
             url: "snippets/adapter-set.php",
             data: { date: getDate },
             success: function(data) {
              // alert(data);
             },
             error: function() {
                 alert("Error.");
             }
        });
    }
  });

});
</script>

 

I'm not going to write the code for you. Instead, I'm going to refer you to my previous post where I said

On 6/30/2021 at 9:15 PM, requinix said:

The date picker only allows one of itself to exist on #datetimepicker1 at a time. Imagine the types of conflicts there could be if it tried to run twice on the same control.

Your first datepicker code needs "highlighted" to know which dates to highlight. Instead of using the variable that comes from $.ajax, use a separate variable, and have the AJAX set that variable. For a brief moment after the page loads, the date picker will be set up and not highlighting any dates, but the user probably won't be able to hit the date picker fast enough to see that being the case.

With the datepicker initialization happening outside of the AJAX, you can more easily combine the beforeShowDay and onSelect options into that configuration object datepicker needs.

Look at your code, read that post again, and decide whether your code is accurately reflected by the statements I made.

1 hour ago, requinix said:

I'm not going to write the code for you. Instead, I'm going to refer you to my previous post where I said

Look at your code, read that post again, and decide whether your code is accurately reflected by the statements I made.

I'm not asking you to redo the whole code. The code I have works. It just needs to be reformatted so both work on the same page. 

And I understand about being only able to using a single datepicker instance. And like I said before, I have tried many different variations  in the past 24 hours and none of them work. So either I keep going in circles or you can help me out and insert your code snippet in the right place into my code. It helps to see it visually.

 

Here's the updated code with what you were trying to say. It doesn't show the Calendar anymore and I get this error in the console "Uncaught SyntaxError: Unexpected identifier".

 

<script>
$(document).ready(function() {

  function formattedDate(d = new Date) {
    let month = String(d.getMonth() + 1);
    let day = String(d.getDate());
    const year = String(d.getFullYear());

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return `${year}-${month}-${day}`;
  }
  //CODE#1
  // THIS CODE FETCHES DATES FROM A MYSQL TABLE AND HIGHLIGHTS THEM ON A DATEPICKER CALENDAR

  var highlighted = null;

  $.ajax({
    type: "POST",
    url: 'snippets/adapter-fetch.php',
    data: {},
    dataType: 'json',
    success: function(data) {

      highlighted = data;

      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,

        beforeShowDay: function(date) {

          newDate = formattedDate(date);

          for(let x=0; x < highlighted.length; x++) {
            console.log(highlighted[x], newDate);

            if (highlighted[x] === newDate) {
              return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
            }
          }
          return [true, '']; // default if not a highlight
        }

        onSelect: function () {
            var getDate = $("#datetimepicker1").val();

            $.ajax({
                 type: "POST",
                 url: "snippets/adapter-set.php",
                 data: { date: getDate },
                 success: function(data) {
                  // alert(data);
                 },
                 error: function() {
                     alert("Error.");
                 }
            });
        }

      });
    }
  });

});
</script>

 

Edited by imgrooot
  • Solution

I found the mistake. All I had to do was to add a "," after the beforeShowday to separate it from the onSelect function. You could've just told me this.

Also I don't even have to create a variable outside the ajax as you previously told me. It works fine without it. 

Here's the updated code.

<script>
$(document).ready(function() {

  function formattedDate(d = new Date) {
    let month = String(d.getMonth() + 1);
    let day = String(d.getDate());
    const year = String(d.getFullYear());

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return `${year}-${month}-${day}`;
  }
  $.ajax({
    type: "POST",
    url: 'snippets/adapter-fetch.php',
    data: {},
    dataType: 'json',
    success: function(highlighted) {

      $('#datetimepicker1').datepicker({
        dateFormat: "yy-mm-dd",
        multidate: true,

        beforeShowDay: function(date) {

          newDate = formattedDate(date);

          for(let x=0; x < highlighted.length; x++) {
            console.log(highlighted[x], newDate);

            if (highlighted[x] === newDate) {
              return [true, 'Highlighted', '']; // that 3rd index is the tooltip text
            }
          }
          return [true, '']; // default if not a highlight
        },

        onSelect: function () {
            var getDate = $("#datetimepicker1").val();

            $.ajax({
                 type: "POST",
                 url: "snippets/adapter-set.php",
                 data: { date: getDate },
                 success: function(data) {
                  // alert(data);
                 },
                 error: function() {
                     alert("Error.");
                 }
            });
        }

      });
    }
  });

});
</script>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.