5

I am using below code to get data from a list later binding to a table but while implementing paging, I am facing some issues.

function GetData(arrayID)
{

$.each(arrayID, function( index, value ) {
if(arrayID[index]!=null)
{
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('test')/items?$select=Array_ID,Title,LAST_NAME,EMPLOYEE_CODE,DESIGNATION,LOCATION&$filter=Array_ID eq '"+arrayID[index]+"'";
$.ajax({  
    url: url,  
    method: "GET",  
    headers: {  
        "Accept": "application/json; odata=verbose"  
    },  
    complete:function(data){   
    },
    success: function(data) {  
    var arrayID = data.d.results[0].ORACLE_HR_ID;
    var employeeName = data.d.results[0].Title + " " + data.d.results[0].LAST_NAME;
    ShowData(ohrID,employeeName);
    },  
    error: function(data) {  
        console.log("error");  
    }  
});  
}
});

$('#tblCustomListData').dataTable({
        paging: true,
        searching: true,
        bDestroy: true,
        "iDisplayLength": 5 ,
        "lengthMenu": [5,10, 25, 50, 100]
    });

});
} 

This is not working perfectly as the code of paging needs to be executed after the completion of .each function. So can I make the paging code to be executed at the end of this .each function?

4

Define your

$.ajax({

as

var call = $.ajax({
// ...
});

Then you can wait until the call is done before you start to populate your dataTable:

call.done(function (data,textStatus, jqXHR){
    $('#tblCustomListData').dataTable({
    // ...
    });
});

There are a few resources for using DataTables with SP, and I'd give a recommendation to have a look at this as the first task.

  • i have tried call.done but this is also firing before the completion of the ajax call – KumarV Jun 6 '17 at 10:46
1

You can't do async ajax inside a loop

You want to wait for each ajax call to be resolved

See an old post: How can I know REST API request done?

for my long answer


Related answer:

  • So is there anything that I can do for code to run after ajax call inside loop – KumarV Jun 6 '17 at 10:48
  • set async:false but don't get agree with me when you code takes loads of seconds to finish.. better to learn to deal with promises as described in the other posts. – Danny '365CSI' Engelman Jun 6 '17 at 11:58
  • even async false is not working to make paging work properly, I know the issue is that I need to execute paging code to run at the end. So still trying for it. – KumarV Jun 6 '17 at 12:16
  • You have to learn to work with (multiple) Promises; for jQuery see stackoverflow.com/questions/4878887/… (the first relevant I found) – Danny '365CSI' Engelman Jun 6 '17 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.