How to change the datasource

How to change the datasource

memrleememrlee Posts: 9Questions: 4Answers: 1
edited September 2015 in Free community support

Hi there. I am a new user to datatables and a relatively new to jquery. I am using the following code to display data in my datatable.

function load_contact_det(contact_type)
{
    // Load data for data table via AJAX
    $.ajax ( {
        url: "./members/contact_det/ajax_contact_det.php?contact_type=" + contact_type,
        method: 'post',
        dataType: 'json',
        success: function (data) 
        {
            var table;
            if ( $.fn.dataTable.isDataTable('#datatables') ) {
                table = $('#datatables').DataTable ();
            } else {
                table = $('#datatables').DataTable ( {
                    data:data,
                    paging: false,
                    searching: false,
                    info: false,
                    columns: [
                        { 'data': 'contact_type' },
                        { 'data': 'contact_det' }
                    ]
                });
            }
        }
    });  

This function is triggered when a user presses one of two buttons (Show Phone No's or Show Email Addresses). My problem is that it displays the correct data intiailly (e.g. telephone data if the user presses the Show Phone No's) but doesn't change the data if the user presses the other button (e.g. Show Email Adddresses) . I know that there is an option to destroy the datatable but I don't think that is the right solution. I also read about the ajax.url and ajax.load functions

table.ajax.url( 'newData.json' ).load(); 

but I am not clear how or where I'd use this in my code. I'm also not sure if I am using the followign statment correctly:

if ( $.fn.dataTable.isDataTable('#datatables') ) 

Any help would be much appreciated.

Just for clarity, regardless of whether the user wants to view telephone numbers or email addresses, the data returned will always be two columns:

a) contact_type (e.g. home tel, personal mobile, work tel, personal email, work email)
b) contact_det (i.e. the physical telephone number or email address)

edited by allan - formatting

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,234Questions: 1Answers: 10,417 Site admin
    Answer ✓

    If you already have the the data available, then use clear() and rows.add() to clear the existing data and then add the new data.

    The ajax methods of the API are only useful if you use ajax to load the data.

    Allan

  • memrleememrlee Posts: 9Questions: 4Answers: 1

    Thank you allan. Much appreciated. Works fine.

This discussion has been closed.