Passing data attributes via ajax using "this"

Passing data attributes via ajax using "this"

snitchysnitchy Posts: 2Questions: 1Answers: 0

Hello, I was wondering if you guys could help me with something that I've been trying to figure out for a few hours now. I don't know if this is possible or if I'm just being stupid, but hopefully you can put me right. I'm not really that great with JavaScript so please forgive me.

What I'm trying to do is retrieve the value of the data attribute on the specific table that DataTables is currently working on. I'm aware that you can currently do this:

$(document).ready(function () {
    $('.example').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: 'scripts/server_processing.php',
            data: function (d) {
                d.custom = $('.example').data('test');
            },
        },
    });
});

But let's say I have multiple DataTables on the page, and I want to pass the specific data attribute for that table. If both of the tables have a class of .example, it will always return the data attribute from the first table. What I would like to do is something like the following:

$(document).ready(function () {
    $('.example').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: 'scripts/server_processing.php',
            data: function (d) {
                d.custom = $(this).data('test');
            },
        },
    });
});

I thought that putting "this" in place of the class of the table would return the data attribute of the table that it's currently working on, but unfortunately this doesn't work and it doesn't return anything at all. Therefore, I was wondering if there is a way to achieve what I'm currently aiming for here?

Any help would be greatly appreciated. Thanks!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,149Questions: 1Answers: 10,404 Site admin
    Answer ✓

    No - that isn't possible at this time. We don't set the scope of the ajax.data function to the table element. Instead, you could do:

    $(document).ready(function () {
      $(".example").each(function () {
        var tableTag = $(this);
    
        tableTag.DataTable({
          processing: true,
          serverSide: true,
          ajax: {
            url: "scripts/server_processing.php",
            data: function (d) {
              d.custom = tableTag.data("test");
            },
          },
        });
      });
    });
    

    Allan

  • snitchysnitchy Posts: 2Questions: 1Answers: 0

    Perfect! Thank you. I did play around with .each during my testing as I suspected that could be a work around, but I can see now where I was going wrong. I've tested it and it works perfectly now.

    Thanks again.

Sign In or Register to comment.