1

I have a problem in my code. I can't change the year values in my Datatable

This code gets the actual year:

var yearDate = new Date();

var year = yearDate.getFullYear();

My datatable method:

$(document).ready(function() {

    januaryTable = $('#january').DataTable({ 

        "processing": true,
        "serverSide": true,
        "order": [],


        "ajax": {
            "url": "<?php echo site_url('gastos/ajax_list/')?>" + year+'-01-01' +'/'+ year+'-01-31',
            "type": "POST",

        },

        "columnDefs": [
            { 
                "targets": [ -1 ],
                "orderable": false,
            },
        ],

    });
}

This code reloads my datatable

function reload_january_table()
{
    januaryTable.ajax.reload(null,false);

}

I change the var year with a select method and it calls the function reload_january_table(), but for example, when I select the value 2016, the table doesn't get values from 2016, it keeps the 2017 values.

Can someone help me ? And sorry for my english if it isn't good.

3
  • How is your select method implemented? Commented Dec 10, 2017 at 11:06
  • It has changed the var year value, because i use it in a function. Commented Dec 10, 2017 at 11:09
  • function Redirect(obj){ var yearO = obj.value; year = yearO; reload_january_table(); reload_january_total_invoice(); } Commented Dec 10, 2017 at 11:11

1 Answer 1

2

The problem is that the ajax.url is only being evaluated when the table is initialised, so the first value of your year variable gets “burnt” in to the url.

The solution is to set the new url for DataTables when the value of year changes like so:

dataTable.ajax.url('NEW_URL').load();

You will find the related part of the DataTables documentation under ajax.url().

In your specific case, you could pass in the new value of year as an argument into the reload_january_table(year) function call and have that function use that like below.

function reload_january_table(year) {
    var newUrl = "<?php echo site_url('gastos/ajax_list/')?>" + year  + '-01-01' + '/' + year + '-01-31';

    januaryTable.ajax.url(newUrl).load();
}
Sign up to request clarification or add additional context in comments.

Comments

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.