Click here to Skip to main content
16,018,938 members
Articles / Web Development

Load Data From Server While Scrolling Using jQuery AJAX

Rate me:
Please Sign up or sign in to vote.
4.90/5 (64 votes)
26 Apr 2012CPOL2 min read 248.6K   9.9K   145   57
This article explains how to implement on-scroll loading data from the server using jQuery as seen on Facebook.

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.

C#
[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 : 

C#
[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.

JavaScript
$(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.

JavaScript
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.

JavaScript
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)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionstatic issues Pin
ftlcd6-Sep-13 12:55
professionalftlcd6-Sep-13 12:55 
GeneralMy vote of 5 Pin
jgakenhe5-Sep-13 5:46
professionaljgakenhe5-Sep-13 5:46 
Questiondata loss when press back button of browser Pin
Shrikrushna S. Ingle17-Aug-13 1:46
Shrikrushna S. Ingle17-Aug-13 1:46 
GeneralMy vote of 5 Pin
Pham Dinh Truong2-May-13 17:01
professionalPham Dinh Truong2-May-13 17:01 
QuestionHow to limit the no of records without repeating Pin
Venkatesh Yeluri17-Mar-13 18:33
Venkatesh Yeluri17-Mar-13 18:33 
AnswerRe: How to limit the no of records without repeating Pin
programet_nje13-Oct-13 22:13
programet_nje13-Oct-13 22:13 
AnswerRe: How to limit the no of records without repeating Pin
programet_nje13-Oct-13 22:25
programet_nje13-Oct-13 22:25 
BugGives error in Jquery Pin
007alok8-Feb-13 0:39
007alok8-Feb-13 0:39 
QuestionGreat Work Pin
hassan133331-Jan-13 20:19
hassan133331-Jan-13 20:19 
QuestionWork Great Pin
amit_8316-Jan-13 23:20
professionalamit_8316-Jan-13 23:20 
QuestionNice article Pin
amit_8315-Dec-12 0:38
professionalamit_8315-Dec-12 0:38 
GeneralAnother Appreciation Pin
wahajahmedansari18-Oct-12 1:04
wahajahmedansari18-Oct-12 1:04 
Questionexplain some lines mean lines Pin
maheshbisht30-Sep-12 22:53
maheshbisht30-Sep-12 22:53 
GeneralMy vote of 5 Pin
Prasad J2-Aug-12 19:42
Prasad J2-Aug-12 19:42 
GeneralMy vote of 5 Pin
_Tushar Patil18-May-12 2:41
_Tushar Patil18-May-12 2:41 
Nice Idea........
QuestionHmmm.. Not a real-world example Pin
Clutchplate10-May-12 6:38
Clutchplate10-May-12 6:38 
Questionfor jQuery AJAX load data Pin
Kien Nguyen Ngoc8-May-12 5:51
Kien Nguyen Ngoc8-May-12 5:51 
AnswerRe: for jQuery AJAX load data Pin
Praveen Meghwal9-May-12 18:56
Praveen Meghwal9-May-12 18:56 
SuggestionMy vote of 5 Pin
Akram El Assas26-Apr-12 22:34
Akram El Assas26-Apr-12 22:34 
GeneralRe: My vote of 5 Pin
Praveen Meghwal29-Apr-12 18:33
Praveen Meghwal29-Apr-12 18:33 
GeneralMy vote of 5 Pin
Monjurul Habib26-Apr-12 21:10
professionalMonjurul Habib26-Apr-12 21:10 
GeneralRe: My vote of 5 Pin
Praveen Meghwal29-Apr-12 18:33
Praveen Meghwal29-Apr-12 18:33 
GeneralMy vote of 5 Pin
Manish Sharma16-Apr-12 23:16
Manish Sharma16-Apr-12 23:16 
GeneralRe: My vote of 5 Pin
Praveen Meghwal29-Apr-12 18:33
Praveen Meghwal29-Apr-12 18:33 
Generalits very usefull Pin
suraj mahajan27-Mar-12 3:06
suraj mahajan27-Mar-12 3:06 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.