1

I'm trying to create a pagination using jquery. I want to return a ajax success response to global Variable. I have created a global variable and stored the response. But I cannot access outside of success block. I want to change the value dynamically, because it will retrive the data when I click the next page without refresh. Thanks in advance..

Code :

  var tmp;
     $('table').DataTable ({
        serverSide:true,
        ajax : {
            url:'http://localhost:8000/api/feeds/1/',
            type:'GET',                
        },drawCallback : function(settings) {

          var api = this.api();
          tmp = api.rows({page:'current'}).data();

        }
      });
    console.log(tmp); 
Dinesh Kumar
  • 483
  • 8
  • 24
  • 1
    this is because ajax is an async call, whereas javascript is synchronous, meaning, your `console.log` gets executed before `tmp` gets assigned. perhaps you could wrap this in a promise, or modify/access `tmp` from your success callback – Napoli Mar 19 '18 at 18:24
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Taplar Mar 19 '18 at 18:25
  • I can't understand about promise. How to handle promise for my problem? – Dinesh Kumar Mar 19 '18 at 18:39
  • you can read this for promise https://stackoverflow.com/questions/10931836/should-i-use-done-and-fail-for-new-jquery-ajax-code-instead-of-success-and – Farhan Mar 19 '18 at 19:13
  • remove var... only put tmp = 0; – Roy Bogado Mar 20 '18 at 17:23

1 Answers1

1

Try this, I have wrapped your request with promise. as suggested by @Napoli in comments

function loadTable(){ 
  $('table').DataTable ({
    serverSide:true,
    ajax : {
      url:'http://localhost:8000/api/feeds/1/',
      type:'GET',                
    },
    drawCallback : function(settings) {
      var api = this.api();
      tmp = api.rows({page:'current'}).data();
      console.log("from api :", tmp);
      return Promise.resolve(tmp);
    },
    error : function( xhr, textStatus, error ) {
      console.log("error", xhr, textStatus, error);
      return Promise.reject(error)
    }
  });
}

loadTable.then(data => console.log("outside loadTable()",data));

I havn't tested this yet, this is just to give you a clear idea.

Shiva Kishore
  • 1,611
  • 12
  • 29