0

$(document).ready(function() {
  let fact = -1;
  // FOREACH_STARTS_HERE
  $('table.tab-<?= $tab_id ?>').DataTable({
    processing: true,
    serverSide: true,
    serverMethod: 'post',
    ajax: {
      url: 'ENDPOINT_URL',
      data: function(pdata) {
        pdata.tab = <?= $tab_id ?>;
        pdata.fact = fact;
      },
      render: $.fn.dataTable.render.text()
    },
  });

  $("#filter_1-<?= $tab_id ?>").click(function() {
    fact = -1;
    $('#filter_1-<?= $tab_id ?>').addClass("active");
    $('#filter_2-<?= $tab_id ?>').removeClass('active');
    $('#filter_3-<?= $tab_id ?>').removeClass('active');
    $('table.tab-<?= $tab_id ?>').DataTable().ajax.reload();
  });

  $("#filter_2-<?= $tab_id ?>").click(function() {
    fact = 0;
    $('#filter_2-<?= $tab_id ?>').addClass("active");
    $('#filter_1-<?= $tab_id ?>').removeClass('active');
    $('#filter_3-<?= $tab_id ?>').removeClass('active');
    $('table.tab-<?= $tab_id ?>').DataTable().ajax.reload();
  });

  $("#filter_3-<?= $tab_id ?>").click(function() {
    fact = 1;
    $('#filter_3-<?= $tab_id ?>').addClass("active");
    $('#filter_1-<?= $tab_id ?>').removeClass('active');
    $('#filter_2-<?= $tab_id ?>').removeClass('active');
    $('table.tab-<?= $tab_id ?>').DataTable().ajax.reload();
  });
  // FOREACH_ENDS_HERE
});
<!-- FOREACH STARTS HERE -->
<li>
  <div>
    <button id="filter_1-<?= $tab_id ?>" class="active">Filter_1</button>
    <button id="filter_2-<?= $tab_id ?>">Filter_2</button>
    <button id="filter_3-<?= $tab_id ?>">Filter_3</button>
  </div>
  <div>
    <div>
      <table id="tab-<?= $tab_id ?>" class="tab-<?= $tab_id ?>">
        <thead>
          <tr>
            <th>Header - 0</th>
            <th>Header - 1</th>
            <th>Header - 2</th>
            <th>Header - 3</th>
            <th>Header - 4</th>
            <th>Header - 5</th>
            <th>Header - 6</th>
            <th>Header - 7</th>
            <th>Header - 8</th>
            <th>Header - 9</th>
            <th>Header - 10</th>
          </tr>
        </thead>
      </table>
    </div>
  </div>
</li>
<!-- FOREACH ENDS HERE -->

I have a javascript that generates multiple DataTable using foreach for each table. I also generate several buttons and javascript functions for each table to filter them through server side.

Currently, I am using foreach to generate .click functions for additional filtering but I felt like this is not correct way of doing this. Sometimes I have up to 10 tables, which makes the following code 3 x 10 click function on single page. I made some research but couldn't find better approach.

Thanks in advance for any guidance, I feel like I am terrible with javascript :)

4
  • 1
    You are correct. It is terrible. All can be solved with a single function using delegation and a loop Commented Oct 29, 2022 at 19:32
  • 1
    Please post a minimal reproducible example using the [<>] snippet editor WITHOUT PHP. Just HTML and script and we can try to save this Commented Oct 29, 2022 at 19:33
  • @mplungjan First of all thank you very much! I tried to do what you said and edited question accordingly, I had to keep some php part to demonstrate how current state of code is. Also mentioned about parts where foreach starts and ends Commented Oct 29, 2022 at 19:49
  • @KIKOSoftware Thank you very much for response, I tried to add HTML and Javascript part with deducting PHP part to express what I am suffering from :) Commented Oct 29, 2022 at 19:50

1 Answer 1

2

Here is the script I would consider. I have not tested it, but you do not need the PHP at all in the script if you use the class

I split filter_1-<?= $tab_id ?> on - to get the tab_id

$(function() {
  let fact = "0";
  $('table').each(function() {
    $(this).DataTable({
      processing: true,
      serverSide: true,
      serverMethod: 'post',
      ajax: {
        url: 'ENDPOINT_URL',
        data: function(pdata) {
          pdata.tab = $(this).attr("id");
          pdata.fact = fact;
        },
        render: $.fn.dataTable.render.text()
      }
    });
  });

  $(".filter").on("click", function() {
    $(this).siblings().removeClass("active")
    $(this).addClass("active");
    const tabID = $(this).attr("id").split("-")[1];
    fact = $(this).data("fact");
    $(`table.tab-${tabID}`).DataTable().ajax.reload();
  });
});
<div>
  <button type="button" id="filter_1-<?= $tab_id ?>" data-fact="-1" class="filter active">Filter_1</button>
  <button type="button" id="filter_2-<?= $tab_id ?>" data-fact="0" class="filter">Filter_2</button>
  <button type="button" id="filter_3-<?= $tab_id ?>" data-fact="1" class="filter">Filter_3</button>
</div>
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you very much for your time and solution! fact is some variable used for filtering and retrieving data from server side. By default its -1 on each button click it should be changed (filter_1 = -1, filter_2 = 0, filter_3 = 1) the value of fact should change and set before ajax.reload() part
See update. Use a data-attribute
Thanks again! I managed to get backend part work, but I have 2 issue, first $(table.tab-${id}) part, I am getting undefined error I believe ${id} should be ${tab} ? Second one is for data-attribute everytime I click on any button, it doesn't post the attribute since it stays undefined.
Yes. I now split the tabID from the id and save the fact in a common variable
It works fine, thanks a lot for all your help and guidance. I learnt a lot from this code about optimization and better usage :)
|

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.