Prashant Pandey Prashant Pandey - 11 months ago 65
Ajax Question

Appending data fetched by an AJAX call to an already existing list for lazy-loading

I am pretty new to UI development, so please, bear with me. I am trying to implement lazy-loading on a webpage. That is, when the user scrolls to the bottom of the page, a page is fetched from the server using an AJAX call. What is wish to do is to append the new data to the already existing one. Currently, the new data occupies the entire list-view and the scroll bar moves to the top. Here is my code:

AJAX call:

$scope.getMoreData=function(){
updateAjaxData();
var url=$scope.getURL();
A.ajax(url, {
method: 'post',
params: AJAX_DATA,
success: function(data, s, x) {
$scope.providersList = JSON.parse(data.serviceproviderlist);
$scope.serviceName = data.category;
$scope.limit = SEARCH_LIMIT;
$scope.$apply();
var div = document.getElementById("spn-service-provider-list");
var content = document.createTextNode($scope.providersList);
div.appendChild(content);
},
error: function(xhr, statusText, errorThrown) {
$scope.errorCallback(xhr);
}
});
}


Here is my HTML:

<div id="spn-service-provider-list">
<div class="spnsearch">
<i class="spnicon spn-icon-search"></i>
<input type="search" ng-model="spsearch" id="spsearch" placeholder="Search Providers" name="spsearch">
</div>
<div id="spn-list" style="height:100vh;overflow-y:scroll;" when-scrolled="showMoreItems(filteredproducts.length,limit)">
<div ng-repeat="providersList in ( filteredproducts = ( providersList | filter:{ providerName: spsearch } | filter:{ citiesServicing: locationsearch }:ignoreNullComparator )) | orderBy: 'rank' | limitTo: limit " >
...................
...................


The problem is that when the new page is fetched using the AJAX call, it occupies the entire list-view. That is, the old list completely vanishes, and the new list occupies its place, with the scroll bar moving to the top.
Further, what is appending to my list successfully is a couple of [object]

Here is the code suggested, still, no change:

success: function(data, s, x) {
if($scope.providersList === null) {
$scope.providersList = []; /* init if null */
}
/* Update the existing array */
Array.prototype.push.apply($scope.providersList, JSON.parse(data.serviceproviderlist));
$scope.serviceName = data.category;
$scope.limit = SEARCH_LIMIT;
$scope.$apply();
viewToBeDisplayed(LIST_VIEW);
},

Answer Source

Because you erase your existing array.
So replace

$scope.providersList = JSON.parse(data.serviceproviderlist);

with

if($scope.providersList == null) {
  $scope.providersList = []; /* init if null */
}
/* Update the existing array */
Array.prototype.push.apply($scope.providersList, JSON.parse(data.serviceproviderlist));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download