Saving dates from DatePicker in cookies and sending date to Datatableat reload

Saving dates from DatePicker in cookies and sending date to Datatableat reload

UboUbo Posts: 3Questions: 1Answers: 0

As my dev is not available I'm trying to progress with my little JQuery knowledge in my project but I'm facing a blocker. I'm trying to create a cookie that will save the date range selected by the user in datepicker and make the report available in datatable when the user refreshes or return to the page.

All I succeeded to do now is create/refresh the cookie when the dates are selected and make the date range selected back on datepicker when the user returns, but the report is not refreshed for those dates as the Ajax request is not sent to datatable.

Here is my code so far:

Code to draw the table

$(document).ready(function(){
                      var todaydate = (new Date()).toISOString().split('T')[0]+"to"+(new Date()).toISOString().split('T')[0];
                      $.ajax({
                        url:"campaign-table.php",
                        method:"POST",
                        data:{todaydate:todaydate},
                        success:function(data){
                          $('#campaigntable').html(data);
                        }
                      });
                    });


                    $('li.dropdown.mega-dropdown').on('click', function (event) {
                      $(this).parent().toggleClass('open');
                    });

                    $('body').on('click', function (e) {
                      if (!$('li.dropdown.mega-dropdown').is(e.target) 
                          && $('li.dropdown.mega-dropdown').has(e.target).length === 0 
                          && $('.open').has(e.target).length === 0) {
                          $('li.dropdown.mega-dropdown').removeClass('open');
                      }
                    });

Code of datepicker and the Ajax request to the table


$('#demo').daterangepicker({ "timePicker24Hour": true, "autoApply": true, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, "alwaysShowCalendars": true, "startDate": Cookies.get('startdate'), "endDate": Cookies.get('enddate'), "opens": "left", }, function(start, end, label) { $("#datereturn").text(start.format('MMMM D, YYYY') + ' to ' + end.format('MMMM D, YYYY')); var todaydate = start.format('YYYY-MM-DD')+"to"+end.format('YYYY-MM-DD'); Cookies.set('startdate', start.format('MM/DD/YYYY')); Cookies.set('enddate', end.format('MM/DD/YYYY')); $.ajax({ url:"campaign-table.php", method:"POST", data:{todaydate:todaydate}, success:function(data){ $('#campaigntable').html(data); } }); });

I need the Ajax request at the end of the code to be executed at page load. I tried the code below. Shorty, it creates cookies at page load if cookie doesn't exist, else it will send the Ajax request to datatable with the dates from the cookies to show the report but it doesn't seem to work:

$(function(){
        var d = new Date();

        var month = d.getMonth()+1;
        var day = d.getDate();

        var output = 
            ((''+month).length<2 ? '0' : '') + month + '/' +
            ((''+day).length<2 ? '0' : '') + day  + '/'
            + d.getFullYear() ;

        if (Cookies.get('startdate')  == null || Cookies.get('enddate') == null) {
              Cookies.set('startdate', output);
              Cookies.set('enddate', output);

        }
        if (Cookies.get('startdate') && Cookies.get('enddate')) {
            var todaydate = Cookies.get('startdate')+"to"+Cookies.get('enddate');
            $.ajax({
                url:"campaign-table.php",
                method:"POST",
                data:{todaydate:todaydate},
                success:function(data){
                    $('#campaigntable').html(data);
              }
            });
        }

    });

As I said, I'm pretty much a newbie with Programmation and I need your help. Thank you.

Answers

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    I'm not clear how this relates to DataTables - it seems more like a cookie issue with DataPicker. It would be worth posting on StackOverlow or a more generic forum to get help there.

    Colin

  • UboUbo Posts: 3Questions: 1Answers: 0

    It's totally related to Datatables. I mentioned DatePicker to explain my issue. The problem I have is loading the table with the date range from the cookies when the user refreshes the page.

    I've already asked on SO and I got no answer for the last 5 days.

  • tangerinetangerine Posts: 3,348Questions: 36Answers: 394

    I don't see a DataTable initialization anywhere in your code.
    Can you post a link to your page, or to a test page showing the issue?

  • UboUbo Posts: 3Questions: 1Answers: 0
    edited April 2020

    Below is my init code. I can't post an example page as it's behind a member area.
    Maybe I'm trying to something that already exists that I'm not aware of.

    In short, the user arrives for the first time on the page and chooses a date range for his report. The data displays on the report and cookies of the start date and end date are created. When the user returns to the page I want him to see the report he has when he left by loading the DT report with the start and end date from the cookies.

    Here is the code. Thank you.

                    var dataTables = $('#example1').DataTable({
                          dom: 'lBrtip',
                          "paging": true,
                          "lengthChange": true,
                          "searching": true,
                          "ordering": true,
                          "info": true,
                          "autoWidth": false,
                          "order": [[ 4, "desc" ]],
                          colReorder: true,
                          stateSave: true,
                          "stateSaveParams": function (settings, data) {
                            data.search.search = "";
                          },
                          "stateDuration": 0,
                          columnDefs: [
                                {
                                    targets: 1,
                                    className: 'noVis'
                                }
                            ],
                            buttons: [
                                {
                                    extend: 'colvis',
                                    columns: ':not(.noVis)',
                                    collectionLayout: 'fixed two-column',
                                    text:      'Edit columns',
                                    titleAttr: 'Edit Columns'
                                
                                }
                            ],
                            language: {
                                buttons: {
                                    colvis: 'Edit columns'
                                }
                            },
                            
                            className: 'btn btn-primary btn-sm m-5 width-140 assets-select-btn toolbox-delete-selected'
    
                        }); 
    
  • kthorngrenkthorngren Posts: 20,275Questions: 26Answers: 4,765
    edited April 2020

    From what I gather from the above this Ajax request is not being executed, correct?

            if (Cookies.get('startdate') && Cookies.get('enddate')) {
                var todaydate = Cookies.get('startdate')+"to"+Cookies.get('enddate');
                $.ajax({
                    url:"campaign-table.php",
                    method:"POST",
                    data:{todaydate:todaydate},
                    success:function(data){
                        $('#campaigntable').html(data);
                  }
                });
            }
    

    If yes, then thats not really a Datatables issue. You will need to start by debugging your code to make sure the if statement is working as expected.

    Kevin

This discussion has been closed.