I want to get a result from server which has huge loads of data. so the server sends the data in multiple pages. so i want to get all those to show them in Datatable. so i use ajax request inside loop because of i want to get from many pages. i add +1 for page variable so the loop will get all the results from all pages until response's no of elements are 0. but the problem is that browser hangs when executing this request? is there any other way to achieve this? thanks.
i tried yo fetch the data first and then add them to table after the loop but still the same hang of browser.
$('#corporateComboOfAllCorpTag').change(function () {
let response=1;
let page=0;
$('#tableOfAllCorpTag').DataTable().destroy();
let corpParkStationTable=$('#tableOfAllCorpTag').DataTable({order:[]});
corpParkStationTable.clear();
let corpStations=[];
while (response!=0){
$.ajax({
url:corporateTagUrl+corporates[$('#corporateComboOfAllCorpTag').prop('selectedIndex')].corporateId,
method:"GET",
data:{
"size":1000,
"page":page
},
dataType:"json",
headers: { 'smart-session-key': sessionKey, 'userName': admin},
async:true,
success:function (resp) {
for (let i = 0; i < resp.content.length; i++) {
corpParkStationTable.row.add($(
'<tr><td>'+resp.content[i].tagSerial+'</td><td>'+resp.content[i].tagUid+'</td><td>'+resp.content[i].status+'</td><td>'+resp.content[i].addedBy+'</td><td>'+resp.content[i].addedDate+'</td><td><button class="btn btn-info">More</button></td></tr>'
)).draw(false);
corpStations.push(resp.content[i]);
}
response=resp.numberOfElements;
},
error:function (resp) {
console.log("Fail "+resp);
}
});
page++;
}
});
If you set async: false
then it will work but some browsers will throw warnings.
I think you have to write your code in sync manner. For example
function getDataFromAjax(){
$('#corporateComboOfAllCorpTag').change(function () {
$('#tableOfAllCorpTag').DataTable().destroy();
let corpParkStationTable=$('#tableOfAllCorpTag').DataTable({order:[]});
corpParkStationTable.clear();
let corpStations=[];
function getPagewiseData(pageNum){
$.ajax({
url:corporateTagUrl + corporates[$('#corporateComboOfAllCorpTag').prop('selectedIndex')].corporateId,
method:"GET",
data:{
size:1000,
page:pageNum
},
dataType:"json",
headers: { 'smart-session-key': sessionKey, 'userName': admin},
async:true,
success:function (resp) {
for (let i = 0; i < resp.content.length; i++) {
corpParkStationTable.row.add($(
'<tr><td>'+resp.content[i].tagSerial+'</td><td>'+resp.content[i].tagUid+'</td><td>'+resp.content[i].status+'</td><td>'+resp.content[i].addedBy+'</td><td>'+resp.content[i].addedDate+'</td><td><button class="btn btn-info">More</button></td></tr>'
)).draw(false);
corpStations.push(resp.content[i]);
}
response=resp.numberOfElements;
if(resp.numberOfElements>0){
getPagewiseData(pageNum+1)
}
},
error:function (resp) {
console.log("Fail "+resp);
}
});
}
getPageWiseData(0);
}
getDataFromAjax();