Naggappan Ramukannan Naggappan Ramukannan - 24 days ago 20
jQuery Question

Get data in json using javascript and datatables

I have a javascript as below, which can fetch the data from backed in json format. But How can i pass it to another function , i.e datatables to populate it

<script>
var returndata;

$.getJSON("/api/dashboard_data/", success);

function success(data) {
returndata = data;
window.alert(returndata);
return returndata;
// do something with data, which is an object
}

$(document).ready(function() {
$('#example').DataTable( {
data: returndata,
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
]
} );
} );
</script>


In above code in window.alert(returndata), i get the json data which has been returned from backed.

But the same variable "returndata" when i use it in function ready it is empty. How can i get it in ready function.

Answer

You are calling two asynchronous functions here. $.getJSON() and $(document).ready(). It looks that ready() is faster than getJSON() which means returndata is empty when you try to fill your data table.

Try this to make sure you have always the correct order:

<script>

$(document).ready(function() {
      $.getJSON("/api/dashboard_data/", function(returndata) {
           $('#example').DataTable( {
               data: returndata,
               columns: [
                    { title: "Action" },
                    { title: "Input" },
                    { title: "State" },
                    { title: "Completed" },
                    { title: "Project" },
               ]
           });
      }); 
});
</script>
Comments