Thursday, December 20, 2012

Load data dynamically on page scroll using jquery,ajax and asp.net.


Introduction

In Facebook you might saw status updates of your friends are dynamically loaded when you scroll the browser’s scroll bar. So in this article i am going to explain how we can achieve this using jQuery and Ajax.

Using the code

The solution includes 2 web forms(Default.aspx and AjaxProcess.aspx). The Default.aspx contain a Div with ID “myDiv“. Initially the Div contain some static data, then data is dynamically appended to the Div using jquery and ajax.
1<div id="myDiv">
2    <p>Static data initially rendered.</p>
3</div>
The second Web Form AjaxProcess.aspx contains a web method GetData(), that is called using ajax to retrieve data.
1[WebMethod]
2    public static string GetData()
3    {
4        string resp = string.Empty;
5        resp += "<p>This content is dynamically appended to the existing content on scrolling.</p>";
6        return resp;
7   }
Now we can add some jquery script in Default.aspx, that will be fired on page scroll and invoke the GetData()method.
01$(document).ready(function () {
02 
03           $(window).scroll(function () {
04               if ($(window).scrollTop() == $(document).height() - $(window).height()) {
05                   sendData();
06               }
07           });
08 
09           function sendData() {
10               $.ajax(
11                {
12                    type: "POST",
13                    url: "AjaxProcess.aspx/GetData",
14                    data: "{}",
15                    contentType: "application/json; charset=utf-8",
16                    dataType: "json",
17                    async: "true",
18                    cache: "false",
19 
20                    success: function (msg) {
21                        $("#myDiv").append(msg.d);
22                    },
23 
24                    Error: function (x, e) {
25                        alert("Some error");
26                    }
27 
28                });
29 
30           }
31 
32       });
Here, to check whether the scroll has moved at the bottom, the following condition is used.
1$(window).scroll(function () {
2               if ($(window).scrollTop() == $(document).height() - $(window).height()) {
3                   sendData();
4               }
5           });
This condition will identify whether the scroll 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 myDiv.
1success: function (msg) {
2                         $("#myDiv").append(msg.d);
3                     },
Download Code
source : http://vivekcek.wordpress.com/tag/jquery-scroll-data-load/