javascript - Changing the url of an Ajax request dynamically - Stack Overflow

I have an ordinary Datatables in my web page, it looks like this:$(document).ready(function() {var tabl

I have an ordinary Datatables in my web page, it looks like this:

$(document).ready(function() {

    var table = $('#mydb').DataTable({
        "serverSide": true,             
        "ajax": "/myapi/?item=free&format=datatables",
        "columns": [

            {data: "item",
            {data: "Price"},

        ]
    });
    setInterval( function () {
    table.ajax.reload();
}, 10000 );
});

This table refreshes every 10 seconds, retrieving the latest values from my database.

Now, i would like to add a button to change dynamically the content of the webpage, so that it retrieves the values from ?item=taken instead of ?item=free, without refreshing the page.

Here is what i tried:

var myvar = 'item=free'

function ChangeVar(){
        myvar = 'item=taken'

    }

$(document).ready(function() {

    var table = $('#mydb').DataTable({
        "serverSide": true,             
        "ajax": "/myapi/?'+ myvar + '&format=datatables",
        "columns": [

            {data: "item",
            {data: "Price"},

        ]
    });
    setInterval( function () {
    table.ajax.reload();
}, 10000 );
});

Html

<button onclick="ChangeVar()" name="button5" type="submit" class="btn btn-primary">See taken items</button>

I added a button that points to the function ChangeVar(), the function should change the main variable's name, which is used in the ajax request. That didn't work, maybe because i'm not using the variable's scope properly, and i think that it wouldn't work because Ajax is asinchronous, so i would need to add something more.

Can someone point me to a solution that would work to this problem?

I have an ordinary Datatables in my web page, it looks like this:

$(document).ready(function() {

    var table = $('#mydb').DataTable({
        "serverSide": true,             
        "ajax": "/myapi/?item=free&format=datatables",
        "columns": [

            {data: "item",
            {data: "Price"},

        ]
    });
    setInterval( function () {
    table.ajax.reload();
}, 10000 );
});

This table refreshes every 10 seconds, retrieving the latest values from my database.

Now, i would like to add a button to change dynamically the content of the webpage, so that it retrieves the values from ?item=taken instead of ?item=free, without refreshing the page.

Here is what i tried:

var myvar = 'item=free'

function ChangeVar(){
        myvar = 'item=taken'

    }

$(document).ready(function() {

    var table = $('#mydb').DataTable({
        "serverSide": true,             
        "ajax": "/myapi/?'+ myvar + '&format=datatables",
        "columns": [

            {data: "item",
            {data: "Price"},

        ]
    });
    setInterval( function () {
    table.ajax.reload();
}, 10000 );
});

Html

<button onclick="ChangeVar()" name="button5" type="submit" class="btn btn-primary">See taken items</button>

I added a button that points to the function ChangeVar(), the function should change the main variable's name, which is used in the ajax request. That didn't work, maybe because i'm not using the variable's scope properly, and i think that it wouldn't work because Ajax is asinchronous, so i would need to add something more.

Can someone point me to a solution that would work to this problem?

Share Improve this question asked Nov 2, 2019 at 10:40 Jack022Jack022 1,3077 gold badges50 silver badges111 bronze badges 1
  • Can you using SESSION or LOCAL storages. – Ahmed Ali Commented Nov 2, 2019 at 10:43
Add a ment  | 

5 Answers 5

Reset to default 4 +50

DataTables has its own method to change ajax URL dynamically: table.ajax.url('URL'). So you don't have to destroy the object and recreate every time.

I have made the example below so the interval reloads for every interval. However, when using table.ajax.url('') you can chain .load() method to retrieve the data immediately.

See this example:

$(document).ready(function() {
  let test = $('#example').DataTable({
    ajax: {
      url: 'https://jsonplaceholder.typicode./posts',
      dataSrc: ''
    },
    columns: [{
        data: 'userId'
      },
      {
        data: 'id'
      },
      {
        data: 'title'
      }
    ]

  });


  changeVar = function() {
    test.ajax.url("https://jsonplaceholder.typicode./albums");
  }

  setInterval(function() {
    test.ajax.reload();
    console.log("Interval");
  }, 10000);

});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables/1.10.11/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables/1.10.11/css/jquery.dataTables.min.css" rel="stylesheet" />

<body>
  <button onclick="changeVar()" name="button5" type="submit" class="btn btn-primary">See taken items</button>
  <br><br>
  <div id="container">
    <table id="example" class="display" cellspacing="0" width="100%">
      <thead>
        <tr>
          <th>ID</th>
          <th>Title</th>
          <th>Body</th>
        </tr>
      </thead>
    </table>
  </div>

</body>

There are one issue with your code

"ajax": "/myapi/?item=free&format=datatables",

When you define an ajax URL, the url will be save on the table instance, so modify variable myvar will not able to change the url inside table instance. But Datatable allow you to change the ajax url though API table.ajax.url(newURL). I also modify the scope of your variable and function, this script bellow will work

var myvar = 'item=free';
var table;
function ChangeVar(){
    myvar = 'item=taken'
    table.ajax.url("/myapi/?'+ myvar + '&format=datatables");
}

$(document).ready(function() {

    table = $('#mydb').DataTable({
        "serverSide": true,             
        "ajax": "/myapi/?'+ myvar + '&format=datatables",
        "columns": [
            {data: "item",
            {data: "Price"},

        ]
    });
    setInterval( function () {
        table.ajax.reload();
    }, 10000 );
});

Do not destroy table and recreate new one, that's not good for performance

You have syntax errors in this code, you are using single quote instead of double quote

"ajax": "/myapi/?'+ myvar + '&format=datatables"

so js takes myvar as a string and not as a variable. try

 "ajax": "/myapi/?"+ myvar + "&format=datatables"

also you missed a closing bracket here {data: "item"

var table = $('#mydb').DataTable({
    "serverSide": true,             
    "ajax": "/myapi/?"+ myvar + "&format=datatables",
    "columns": [

        {data: "item"},
        {data: "Price"},

    ]
});

Try like this

function refreshDataTable(itemName) {
    var table = $('#mydb').DataTable({
        "serverSide": true,
        "ajax": "/myapi/?'+ myvar + '&format=datatables",
        "columns": [
            {data: "item"},
            {data: "Price"},
        ]
    });
    setInterval(function () {
        table.ajax.reload();
    }, 10000);
}

$(document).ready(function () {
    refreshDataTable('item=free');
    $('#change-item-btn').on('click', function (e) {
        e.preventDefault();
        refreshDataTable('item=taken');
    });
});

And in HTML

<button id="change-item-btn" name="button5" type="submit" class="btn btn-primary">See taken items</button>

Good luck, keep coding.

You have to destroy and reinitialise the Datatable each time.

var table = null;

function ChangeVar() {
  table.destroy();
  table = $("#mydb").DataTable({
    serverSide: true,
    ajax: "/myapi/?item=taken&format=datatables",
    columns: [{ data: "item" }, { data: "Price" }]
  });
}

$(document).ready(function() {
  table = $("#mydb").DataTable({
    serverSide: true,
    ajax: "/myapi/?item=free&format=datatables",
    columns: [{ data: "item" }, { data: "Price" }]
  });
  setInterval(function() {
    table.ajax.reload();
  }, 10000);
});

more info: https://datatables/manual/tech-notes/3#destroy

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745402226a4626154.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信