I have used a code that I got from a site for infinite scrolling using knockout js, with some changes in it.
Here's my html and javascript code:
<div id="main" data-bind="foreach: items, event: { scroll: scrolled }">
<div data-bind="text: name"></div>
</div>
<script type="text/javascript">
var viewModel = {
items: ko.observableArray([]),
scrolled: function(data, event) {
var elem = event.target;
if (elem.scrollTop > (elem.scrollHeight - elem.offsetHeight - 200)) {
getItems(6);
}
},
maxId: 0,
pendingRequest: ko.observable(false)
};
function getItems(cnt) {
if (!viewModel.pendingRequest()) {
var entries = [];
for (var i = 0; i < cnt; i++) {
var id = viewModel.maxId++;
entries.push({
id: id
});
}
viewModel.pendingRequest(true);
$.ajax({
type: 'POST',
url: 'echojson.php',
data: {
json: ko.toJSON(entries),
delay: .1,
id:id,
cnt:cnt
},
success: function(entries) {
ko.utils.arrayForEach(entries, function(entry) {
alert(entry);
viewModel.items.push(entry);
});
viewModel.pendingRequest(false);
},
error: function() {
viewModel.pendingRequest(false);
},
dataType: 'json'
});
}
}
ko.applyBindings(viewModel);
getItems(6);
</script>
And here is the php file code from where I am getting the data:
<?php
include 'dbconfig.php';
$jsonarr=json_decode($_POST['json'],true);
$cnt=$_POST['cnt'];
if(isset($_POST['id'])){
$offset=$_POST['id'];
}
if($offset<=$cnt){
$offset=0;
}
else{
$offset=$offset-($cnt-1);
}
$json=array();
$sql="SELECT * FROM user LIMIT $offset,".$cnt;
$exec=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($exec)){
$name=strtoupper($row['fname'].' '.$row['lname']);
$profilepic=$row['profilepic'];
$city=$row['city'];
$json[]=$name.' '.$profilepic.' '.$city;
}
echo json_encode($json);
?>
On scroll, I get the correct number of div added but the data in items
array is not displayed in the div with id main
.
When I alert elements in array items, I do get the values in it. But this updated array is not getting binded to the div it seems.
Please help me fix this.
Your server side logic is incorrect. You are sending back an array of strings and not an array of objects. So when you get the data on the client side your items does not have a name
property.
So you need to add objects in your $json
array which has the correct property names, there are multiple ways to do it (use proper classes or use anonymous types) , here is one example:
$json[]= (object)array('name' => $name, 'profilepic' => $profilepic, 'city' => $city);