Click here to Skip to main content
Click here to Skip to main content

Load Data From Server While Scrolling Using jQuery AJAX

By , 26 Apr 2012
 

Introduction

This article will demonstrate how to load data from the server while scrolling. Loading data from the server using AJX will help any application in improving its performance because data which is displayed on the screen alone is loaded the first time and more data, if required, will get loaded from the server as the user scrolls.

Background

Facebook is the application which inspired me to write code to load data from the server while scrolling. While browsing Facebook, I was amazed to see that as I scrolled on the page, new data from the server got appended to the existing one. I became curious about implementing the same functionality in C#. I searched for information, but did not find any article or blog on doing this in C#. Of course, there were a few articles for Java and PHP. I read them carefully and started writing code in C#. As it worked successfully I thought I'd share it, so I am posting it here.

The code

To implement the load on scroll functionality, we will require very few lines of code. A WebMethod that will be called from the client side which returns the content to append while scrolling, and a client side function (document.ready) where we will bind the scroll event to load data from the server. Let us see these server and client side methods in detail.

Server method: This method is used to get data from the database or any source and prepares an HTML string depending on the control you are using for appending data to. Here I have just added a message with the serial number.

[WebMethod]
public static string  GetDataFromServer() 
{ 
    string resp = string.Empty; 
    for(int i = 0; i <= 10; i++)
    {
        resp += "<p><span>"  + counter++ + 
          "</span> This content is dynamically appended " + 
          "to the existing content on scrolling.</p>" ; 
    } 
    return resp; 
} 

If you want to load data from database you can modify your method as follows : 

[WebMethod]
public static string GetDataFromServer()
    {
        DataSet ds = new DataSet();
 
        // Set value of connection string here
        string strConnectionString = ""; // Insert your connection string value here
        SqlConnection con = new SqlConnection(strConnectionString);
 
        // Write the select command value as first parameter
        SqlCommand command = new SqlCommand("SELECT * FROM Person", con);
        SqlDataAdapter adp = new SqlDataAdapter(command);
int retVal = adp.Fill(ds);
 
        string resp = string.Empty;
for (int i = 1; i <= ds.Tables[0].Rows.Count; i++)
        {
            string strComment = string.Empty;
if (ds.Tables != null)
            {
if (ds.Tables[0] != null)
                {
if (ds.Tables[0].Rows.Count > 0)
                    {
if (ds.Tables[0].Rows.Count >= i - 1)
                        {
if (ds.Tables[0].Rows[i - 1][0] != DBNull.Value)
                            {
                                strComment = ds.Tables[0].Rows[i - 1][0].ToString();
                            }
                        }
                    }
                }
            }
            resp += "<p><span>" + counter++ + "</span> " + strComment + "</p>";
        }
return resp;
    }  

Client method: At the client side, I have used the document.ready method in which I have registered event binding for scroll on div. I have used two div elements: mainDiv and wrapperDiv. I have registered the scroll event for mainDiv and append dynamic data to wrapperDiv.

$(document).ready( 
function()
{
$contentLoadTriggered = false;
$("#mainDiv").scroll(
function()
{
if($("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - 
   $("#mainDiv").height()) &&
   $contentLoadTriggered == false)
   $contentLoadTriggered == false)
{
$contentLoadTriggered = true;
$.ajax(
{
type: "POST",
url: "LoadOnScroll.aspx/GetDataFromServer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) 
{
$("#wrapperDiv").append(msg.d);
$contentLoadTriggered = false;
},
error: function (x, e)
{
alert("The call to the server side failed. " +
x.responseText);
}
}
);
}
}
);
}
);

Here, to check whether the scroller has moved at the bottom, the following condition is used.

if($("#mainDiv").scrollTop() >= 
  ($("#wrapperDiv").height() - $("#mainDiv").height()) &&
   $contentLoadTriggered == false)

This condition will identify whether the scroller has moved at the bottom or not. If it has moved at the bottom, dynamic data will get loaded from the server and get appended to wrapperDiv. The client script to append data to the desired div element is written in the script to run when the asynchronous call results in success.

success: function (msg)
{
$("#wrapperDiv").append(msg.d);
$contentLoadTriggered = false;
}

Here one thing you will notice is that the request will go to the server only when the user has scrolled at the bottom.

I have attached the sample application with this article.

Output

LoadOnScroll/LOS1.JPG

LoadOnScroll/LOS2.JPG

History

First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Praveen Meghwal
Software Developer (Senior)
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberPham Dinh Truong2 May '13 - 17:01 
Great article. Thanks.
QuestionHow to limit the no of records without repeatingmemberVenkatesh Yeluri17 Mar '13 - 18:33 
How can I stop retrieving the same data when it is already show on the page.
 
Ex: If I have 10 records in my DB, those 10 records are repeating the no of times I scroll down. Once I have shown the records, how to stop it and display a message. "No more records"
 
Thanks
BugGives error in Jquerymember007alok8 Feb '13 - 0:39 
While fetching the data from database jquery shows syntax error i am not good in Jquery so can't resolve this issue
if($("#mainDiv").scrollTop() >= ($("#wrapperDiv").height() - $("#mainDiv").height()) && $contentLoadTriggered == false) $contentLoadTriggered == false)
This lines shows ; exepected
QuestionGreat Workmemberhassan133331 Jan '13 - 20:19 
I was looking for this functionality for some time! Thumbs Up | :thumbsup:
QuestionWork Greatmemberamit_8316 Jan '13 - 23:20 
Hi,
 
This work great.
But i have a question
On scroll i am persisting the scroll position with load on demand functionality.
to maintain the scroll position after page postback.
So both are working fine.
But when i select any item then my list is flickering to set the scroll position
where i have stopped my scroll. if i remove load on demand then flickering does not
happen to set the scroll position on pagepost back.
What should i do to resolve this issue?
or Do you have any guess to resolve this issue?
Problem comes in IE 9 only not in chrome.
QuestionNice articlememberamit_8315 Dec '12 - 0:38 
Hi,
 
Thanks for sharing such a nice article.
 
My data is loading successfully when scroll the page. but when my page post back then
Loading data (OnScroll) has been lost. what should i do to resolve this issue?
 
Note: my list is inside the UpdatePanel
GeneralAnother Appreciationmemberwahajahmedansari18 Oct '12 - 1:04 
Simple and Light, Hats off.
Questionexplain some lines mean linesmembermaheshbisht30 Sep '12 - 22:53 
thanks,your article is good and really helpful for me and others.from my personal way i m unable to understand a line in this example that a line is "$("#wrapperDiv").append(msg.d);"
please explain it why we use msg.d (why we use d with msg) or i want to binds a row in table will it work.what i have to make a change on it , please guide it or [webmethod] attribute is use to tell compiler that this method is use in a web service then why we use it here please explain to clear it use here.especially i have a doubt on return type how i have to do it,A personal request i can i ask doubt on your mail plz give me your mailid.
GeneralMy vote of 5memberPrasad J2 Aug '12 - 19:42 
nice..
GeneralMy vote of 5memberTushar_Patil18 May '12 - 2:41 
Nice Idea........
QuestionHmmm.. Not a real-world examplememberClutchplate10 May '12 - 6:38 
Thanks for explaining the method for doing this, but clearly this is very simplistic code.
In a real app, you would need to keep track of the data you've already retrieved and displayed and pass that back in the POST to just get the new data. Similarly, you'll want to use better SQL than "SELECT * FROM" to get the data...
 
But a good explanation nonetheless Smile | :)
- Lutz

Questionfor jQuery AJAX load datamemberKien Nguyen Ngoc8 May '12 - 5:51 
cool, thanks for share
AnswerRe: for jQuery AJAX load datamemberPraveen Meghwal9 May '12 - 18:56 
Thanks
SuggestionMy vote of 5memberAkram El Assas26 Apr '12 - 22:34 
Nice.
 
You can also do it with a HttpHandler.
 
It would be more interresting to add pagination in a stored proecedure, use JSON and add an ajax animation while data is beeing loaded like in twitter. The stored procedure will return a fixed size of rows (20 for instance) and the Webmethod or HttpHandler will return a JSON array of records that will be displayed on the client.
GeneralRe: My vote of 5memberPraveen Meghwal29 Apr '12 - 18:33 
Thanks
GeneralMy vote of 5memberMonjurul Habib26 Apr '12 - 21:10 
nice one!
GeneralRe: My vote of 5memberPraveen Meghwal29 Apr '12 - 18:33 
Thanks
GeneralMy vote of 5memberManish Sharma16 Apr '12 - 23:16 
Hi, This is Manish Sharma From Lucknow,those who wants to learn Json,Jquery & all asynchronous medium..may read this article..great work
GeneralRe: My vote of 5memberPraveen Meghwal29 Apr '12 - 18:33 
Thanks Manish
Generalits very usefullmembersuraj mahajan27 Mar '12 - 3:06 
thanks to creator .
its very usefull . Smile | :)
GeneralRe: its very usefullmemberPraveen Meghwal27 Mar '12 - 19:23 
thanks
QuestionMy vote of 5memberNguyen Quy Minh22 Feb '12 - 5:10 
Very great article.
Live free, die well!
http://www.sirvina.com

AnswerRe: My vote of 5memberPraveen Meghwal22 Feb '12 - 20:05 
Thanks
QuestionThanks for sharing such a nice article.memberZaheer Mazhar5 Jan '12 - 5:37 
Thank you for sharing such a nice article.
AnswerRe: Thanks for sharing such a nice article.memberZaheer Mazhar5 Jan '12 - 6:22 
I only want to ask one thing that if i want to assiciate this scroll functionality with right side scroller like in facebook, then which code we will need to change? I don't want to use little maindiv, in place of this i want to use the default scrolling in browser and want to associate callback based on that scroller. Can you guide me.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 27 Apr 2012
Article Copyright 2011 by Praveen Meghwal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid