0

I want to create a general function to initialise all my ajax DataTables.

I need to be able to identify the table that is requesting data so my server-side script knows which data to send back.

I thought I'd simply be able to attach the table ID to the ajax URL like so:

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": {
            "url": "www.example.com/load-" + this.id + ".php"
        }
    });
});

I thought the URL would resolve to "www.example.com/load-example.php" but it didn't work as this.id is undefined (as is $(this).attr('id')) so I thought maybe I could use a single server-side script and pass in an extra $_GET parameter like so:

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": {
            url: "www.example.com/load-table.php",
            data: function ( d ) {
                d.experiment = this.id;
            }
        }
    });
});

This also failed for the same reason.

Is it possible to get the table ID when retrieving data this way?

1 Answer 1

1

I've found a solution that works but if someone has a better way, please post your solution here.

This solution binds to any table that has the class 'data-table'.

$(document).ready(function() {
    $('.data-table').each(function(index) {
        var table = this.id;
        $(this).DataTable({
            "ajax": {
                "url": "www.example.com/load-" + table + ".php"
            }
        });
    });
});
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.