I am trying to do infinite scroll in my .NET website, using javascript and the following sql statement (sql server 2008). This sql gets the first 10 rows, but my javascript causes the sql to execute each time the user scrolls to the bottom of the page, and each time, it pulls the same (first 10) records, but I want it to pull the NEXT 10 records, each time user scrolls to the bottom. How do I use this sql and row_number to get the NEXT 10 rows, each time user scrolls to bottom of page?
SELECT * FROM
(SELECT ROW_NUMBER() OVER (ORDER BY DateTime) As RowNum,
* From Topic) As a
WHERE RowNum
BETWEEN 1 AND 10
Here is the javascript:
<script type="text/javascript">
$(document).ready(function () {
function lastPostFunc() {
$('#divPostsLoader').html('<img src="images/bigLoader.gif">');
//send a query to server side to present new content
$.ajax({
type: "POST",
url: "Default.aspx/Foo",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
$('.divLoadData:last').after(data.d);
}
$('#divPostsLoader').empty();
}
})
};
//When scroll down, the scroller is at the bottom with the function below and fire the lastPostFunc function
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
lastPostFunc();
}
});
});
</script>
I now have the above sql in stored procedure:
<System.Web.Services.WebMethod()>
Public Shared Function Foo() As String
Dim strConn As String = "Data Source="
Dim conn As New SqlConnection(strConn)
Dim Cmd As New SqlCommand("InfiniteScroll", conn)
Cmd.CommandType = CommandType.StoredProcedure
Dim DA As New SqlDataAdapter(Cmd)
Dim DS As New DataSet()
DA.Fill(DS, "RefologyForumTopic")
Dim getPostsText As New StringBuilder()
Dim dv As DataView = DS.Tables(0).DefaultView
For Each myDataRow As DataRowView In dv
getPostsText.AppendFormat("price: {0}</br>", myDataRow("Topic"))
getPostsText.AppendFormat("description: {0}</br></p>", myDataRow("UserID"))
Next
getPostsText.AppendFormat("<div style='height:15px;'></div>")
Return getPostsText.ToString()
End Function
Typically we do this using a stored procedure passing in a page and/or result counter parameters. Something like this:
Here is the SQL Fiddle.
–EDIT
This is all untested, but should get you going in the right direction:
First, add a hidden page to the page to store your current page number:
Second, update your data parameters in your ajax call:
Third, update your web method to accept the param:
Then update your SQL to pass the parameter. I’m not going to rewrite that, but use this link for assistance: http://msdn.microsoft.com/en-us/library/bbw6zyha(v=vs.71).aspx
And finally, reset your hidPage variable on your ajax success handler.
Good luck.