I am trying to save data from a link in JSON format and pass that data to the Bootstrap table but its not working properly
I can see the data in console and if I use data-url
than it works fine but I want to save data in a variable and use that data in table.
If I use this code than it works fine, but I want to save data into a variable first and than assign it to table.
$.get("https://api.github.com/users/wenzhixin/repos", function(data){
$('#table').bootstrapTable({
data: data
});
});
Since you mentioned the only idea to store the data into a variable is for re-useablity you can do below. Working Fiddle
var jsonDataCall ; // keep a global variable in the scope.
$(function() {
$.get("https://api.github.com/users/wenzhixin/repos", function(result){
jsonDataCall = result; // save it to a variable for later use
$('#table').bootstrapTable({
data: jsonDataCall // use the same variable to build the table
});
});
});
By the way async
is deprecated and you shouldn't be using it anymore more details here and here
Explaining problem in your code provided in jsfiddle:
var jsonDataCall = $.getJSON("https://api.github.com/users/wenzhixin/repos", function(result){
jsonDataCall =result;
});
var jsonData = $.ajax({ // this variable is not used anywhere in the code.
async: false,
dataType: "json",
url: "https://api.github.com/users/wenzhixin/repos",
success: function(result) {
jsonData = result;
}
});
$(function () {
var $table = $('#randomTable').bootstrapTable({data: jsonDataCall});
});
This line var $table = $('#randomTable').bootstrapTable({data: jsonDataCall});
kicks off on document ready. And here we have jsonDataCall
which will access the value in it. But in the first line you have assigned a ajax method to this variable and not a value. So the in the above line data: jsonDataCall
will try to assign the ajax function to data variable it does not assign the value returned from server because it comes later after the ajax success has executed.
Solution: When ever you are dealing with ajax calls you must make sure all the code that depends on the returned server result should kick off in the ajax success else you are in trouble.