Total Item Count
If you are looking for the total number of items in the list itself (as opposed to the number of items in a filtered view) you can directly access the list's $count
property.
"/_vti_bin/ListData.svc/MPIC/$count"
This will return the item count.
Paging (if necessary)
To simulate paging using REST you can do the following:
- Use the
$skip=n
parameter to skip the first n
entries according to the $orderby
parameter
- Use the
$top=n
parameter to return the top n
entries according to the $orderby
and $skip
parameters.
Dealing with Asynchronous Callbacks
The biggest problem in your code is that you've got two asynchronous function callbacks that you use to get the sum of resulting items. Since those function calls are not executed within the same scope, you can't access their values simultaneously.
A workaround is to use function chaining to move your logic forward into the callback function(s).
Example using $skip and $top
Here's an example using the $skip
and $top
parameters with your provided code, using a recursive callback function to get the total number of results before updating the text of your ALLCount1
element.
$.getJSON("/_vti_bin/ListData.svc/MPIC?$select=Id&$orderby=Id&$top=1000&$inlinecount=allpages", function (data) {
var count = data.d.results.length;
updateTotal(count);
});
function updateTotal(total){
$.getJSON("/_vti_bin/ListData.svc/MPIC?$select=Id&$orderby=Id&$skip="+total+"&$top=1000&$inlinecount=allpages", function (data) {
var count = data.d.results.length;
if(count > 0){
updateTotal(total+count);
}
else{
$("#ALLCount1").text(total);
}
});
}
Example using $skiptoken and $top
If you're constrained to use $skiptoken
instead of $skip
(such as when querying a list of 5000+ items), you can definitely still use it, but you'll have a bit more work to do.
Whereas $skip
just wants the number of items to skip, $skiptoken
wants the ID of the last item to skip.
The code would be mostly the same as above, but you'll need to dive into the data results and pluck out the last item's ID value. I'll leave that as an exercise for the reader.
updateTotal(0,0);
function updateTotal(skip,total){
$.getJSON("/_vti_bin/ListData.svc/MPIC?$select=Id&$orderby=Id&$skiptoken="+skip+"&$top=1000&$inlinecount=allpages", function (data) {
var count = data.d.results.length;
if(count > 0){
var lastItemId;
// TODO: get last item id from results here
updateTotal(lastItemId,total+count);
}
else{
$("#ALLCount1").text(total);
}
});
}