jQuery DataTables reload interval error

2019-08-23 08:16发布

I'm trying to get my table to load on intervals. I am now receiving the below error:

TypeError: g is null

The user will enter form parameters and then hit the submit button which has a click event. As follows:

$('.searchSubmit').on('click', function()
{
  var data = {
    searchCriteria: {
      bill: $('#import_bill').val(), 
      ramp: $('#import_ramp').val(), 
      // few other parameters
    }
  };

  $.ajax({
    url: 'api/railmbs.php',
    type: 'POST',
    data: data,
    dataType: 'html',
    success: function(data, textStatus, jqXHR)
    {
      var jsonObject = $.parseJSON(data); 
      var table = $('#example1').DataTable({    
        "data": jsonObject,
        "columns": [
          { "data": "BILL" },   
          { "data": "RAMP" },   
          // few more columns
        ],
        "iDisplayLength": 25,
        "paging": true,
        "bDestroy": true,
        "stateSave": true,
        "autoWidth": true
      });

      var idle = 0;
      var idelInterval = setInterval(timer, 10000);
      $(this).mousemove(function(e){idle = 0;});
      $(this).keypress(function(e){idle = 0;});
      function timer()
      {
        idle = idle + 1;
        if(idle > 2)
        {
          $('#example1').DataTable().ajax.reload();  // <--error occurs here
          console.log('table reloaded');        
        }
      }
    },
    error: function(jqHHR, textStatus, errorThrown)
    {
      console.log('fail');
    }
  });
});

Here's the funny part...above, where I pointed to where the error was occurring, I originally had it looking like this:

$('#example').DataTable().ajax.reload(); 

Notice the table name was 'example' instead of 'example1'. The table ID is indeed example1, as I indicated up near where the success function begins. When I saw the reload interval was looking at a different table ID, I changed it, which now is causing the error at the top.

I don't think I should keep the ID as 'example' because that is not the correct ID.

With that said, why am I getting the error?

2条回答
趁早两清
2楼-- · 2019-08-23 09:05

How do you expect ajax.reload() to work? There is no AJAX in use and therefore no previous AJAX to reload. Do this instead (schematic) :

var table = $('#example1').DataTable({    
   ajax: {
     url: 'api/railmbs.php',
     data: function() {
        return { 
          searchCriteria: {
            bill: $('#import_bill').val(), 
            ramp: $('#import_ramp').val(), 
            // few other parameters
          } 
        }
     }
   },
   "columns": [
      { "data": "BILL" },   
      { "data": "RAMP" },   
      // few more columns
   ],
   "iDisplayLength": 25,
   "paging": true,
   "bDestroy": true,
   "stateSave": true,
   "autoWidth": true
});

Now you should be able to table.ajax.reload() from anywhere where table is available.

查看更多
在下西门庆
3楼-- · 2019-08-23 09:13

I've worked out a solution that seems to do the trick. I tried to keep this as simple as I could, while still incorporating jQuery and (I think) solving the issue you were having.

index.html

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax Reloader</title>
</head>

<body>

    <header>
        <h1>AJAX Reloader</h1>
    </header>

    <section>
        <form id="theForm">
            <input id="theButton" type="button" value="Click me to load data">
        </form>
    </section>

    <section>
        <p>
        <h3>Data Reload in: <span id="reloadCounter">5</span></h3>
    </section>

    <section>
        <table id="theTable"></table>
    </section>

    <template id="theTemplate">
        <tr>
            <td>Name:</td>
            <td data-js></td>
        </tr>
    </template>

    <script
        src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous">
    </script>

    <script>
        (function() {
            const $btn = $('#theButton');
            const $tbl = $('#theTable');
            const $tmpl = $('#theTemplate');
            const $span = $('#reloadCounter');

            let isLoading = false;
            let counter = 5;

            // Load data on Button click.
            $btn.click(() => {
                loadData(true);
            });

            // Auto-reload table data every 5 seconds.
            // Add a countdown, just for gits and shiggles
            window.setInterval(() => {
                if (counter === 0) {
                    loadData(false);
                    counter = 5;
                } else {
                    counter--;
                }

                $span[0].textContent = counter.toString();

            }, 1000);

            function loadData(isBtnClick) {
                if (!isLoading) {
                    isLoading = true;

                    let file = (isBtnClick) ? 'data1' : 'data2';

                    $.ajax({
                        url: `./${file}.json`,
                        type: 'GET',
                        dataType: 'json',
                        success: (data, status) => {
                            console.log('loadData::success - Got data!', data);
                            $tbl[0].innerHTML = '';

                            let td = $tmpl[0].content.querySelector('td[data-js]');

                            data.forEach((item, idx, arr) => {
                                td.textContent = item.name;
                                let tr = document.importNode($tmpl[0].content, true);
                                $tbl[0].appendChild(tr);
                            });

                            isLoading = false;
                        }
                    });

                    if (isBtnClick) {
                        console.log('loadData - Button clicked');
                    } else {
                        console.log('loadData - Interval triggered');
                    }
                }
            }
        })();
    </script>
</body>
</html>

data1.json

[
  {"name": "Rincewind"},
  {"name": "Mustrum Ridcully"},
  {"name": "Ponder Stibbons"},
  {"name": "Gaspode The Wonder Dog"},
  {"name": "CMOT Dibbler"},
  {"name": "Nanny Ogg"}
]

data2.json

[
  {"name": "Jason Ogg"},
  {"name": "Tiffany Aching"},
  {"name": "Rob Anybody"},
  {"name": "Mrs. Cake"},
  {"name": "Nobby Nobbs"},
  {"name": "Fred Colon"}
]

My style of coding is a little different from yours, but the same basic concepts should be in play here.

Hope it helps. :-)

查看更多
登录 后发表回答