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?

2 Answers 2

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.

1
  • i have tried call.done but this is also firing before the completion of the ajax call
    – KumarV
    Commented Jun 6, 2017 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:

4
  • So is there anything that I can do for code to run after ajax call inside loop
    – KumarV
    Commented Jun 6, 2017 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. Commented Jun 6, 2017 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
    Commented Jun 6, 2017 at 12:16
  • You have to learn to work with (multiple) Promises; for jQuery see stackoverflow.com/questions/4878887/… (the first relevant I found) Commented Jun 6, 2017 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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