Limitless scrolling functionality in asp.net

I attempted to implement an infinite scroll feature using a WebMethod, but I keep receiving a "failed" message. After reviewing my code, I couldn't identify any errors. Below is the code snippet:

Code Behind:

public int CurrentPage
    {
        get
        {
            // check for current page in ViewState
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0;    // default to displaying the first page
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        sqlConn.ConnectionString = ConfigurationManager.AppSettings["Database"];        
        ItemsGet("EN");
    }



[WebMethod]
    public void ItemsGet(string Language)
    {

        try
        {

            sqlConn.Open();

            SqlDataAdapter myCommand = new SqlDataAdapter(@" Database query...", sqlConn);

            DataSet ds = new DataSet();

            myCommand.Fill(ds);

            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = ds.Tables[0].DefaultView;
            objPds.AllowPaging = true;
            objPds.PageSize = 9;

            objPds.CurrentPageIndex = CurrentPage;

            Repeater1.DataSource = objPds;
            Repeater1.DataBind();

        }
        catch (Exception ex)
        {

        }

    }

ASPX:

<asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <ul class='hover_block'>
                                         <li style=''>
                                 <a style='width: 524px;margin-top:-1px;margin-left:-1px; height: 365px;border:1px solid #cecece; background-color: #ECecec;' href='  <%#DataBinder.Eval(Container.DataItem,"RecID") %>'>
                                     <img src='abc.com.tr/news/img/<%#DataBinder.Eval(Container.DataItem,"Image1")%>' alt='' class='left' style='margin-right: 10px; width: 500px; height: 300px;'/>
                                     <div class='Icerik'>
                                        <h3 class='News_Head'> <%#DataBinder.Eval(Container.DataItem,"Head") %></h3>
                                        <p style='font-family:Tahoma;'> <%#DataBinder.Eval(Container.DataItem,"Content") %></p>
                                        <b class='info'>View More</b>
                                    </div>
                                </a>

                            </li>
                        </ul>
            </ItemTemplate>
        </asp:Repeater>

JavaScript Side:

 <script type="text/javascript">
        $(window).scroll(function () {
            if ($(window).scrollTop() == $(document).height() - $(window).height()) {


                $.ajax({
                    type: "POST",
                    url: "default.aspx/ItemsGet",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: AjaxSucceeded,
                    error: AjaxFailed
                });

                function AjaxSucceeded() {
                    alert("result.d");
                }
                function AjaxFailed() {
                    alert("Failed");
                }
            }
        });</script>

What could be causing the failure? I consistently receive the alert("Failed") message while scrolling. Any assistance would be greatly appreciated. Thank you for your responses.

Answer №1

Here's an easy and quick way to achieve this:

<script type="text/javascript" language="javascript>
    $(document).ready(function () {

        $(window).scroll(function () {
            if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                sendData();
            }
        });

        function sendData() {
            $.ajax(
            {
                type: "POST",
                url: "AjaxProcess.aspx/GetData",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: "true",
                cache: "false",

                success: function (msg) {
                    $("#myDiv").append(msg.d);
                },

                Error: function (x, e) {
                    alert("Some error");
                }

            });

        }

    });


</script>
</head>
<body>
<form id="form1" runat="server>
<div id="myDiv>
</div>
</form>
</body>

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Placing drop-down animations in just the right spot

I'm currently working on adjusting the dropdown behavior for thumbnails when hovering over them. I want the drop-down to appear beneath the 'Caption Title' instead of above the image, but so far my CSS adjustments haven't been successfu ...

Using PHP, HTML, and JavaScript to generate a dropdown list from a database

I am looking to create a dynamic dropdown list populated from a database using JavaScript. My goal is to design a form where users can add multiple rows by clicking the "add more" button. The form will include both a text input field and a dropdown list. ...

Tips for formatting the JSON date format in a Spring Boot application

I'm currently working on setting up a rest service using Spring Boot and Gradle. My goal is to format the JSON date in the "yyyy-MM-dd" form, specifically for the dateOfBirth field to be displayed as "16-03-2015". However, I'm running into an iss ...

How can the node version be set globally in NVM?

While utilizing Node Version Manager, setting the node version to the latest one in the current directory can be done using nvm use node. But how can you specify a specific version to use? ...

What is the appropriate time to end a connection in MongoDB?

Utilizing Node.js Express and MongoDB for my API, I encountered an issue with the mongoClient connection. The data fetching process worked smoothly at first, but without refreshing it threw an error stating "Topology is closed." const express=require("e ...

Setting up multiple versions of npm application

Can I have multiple versions of npm installed for different projects on Windows 10, or are npm installations always global? I attempted to install different versions using https://github.com/marcelklehr/nodist, but it only affected the node version and no ...

Error: The symbol $ is not recognized

This is a snippet of code that I've written to automate address filling and extract latitude/longitude/address information. <html> <head> <LINK rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" sr ...

Obtaining an image from a URL, saving it, and then animating it? That definitely

Looking to create a dynamic animation with images that update every 15 minutes from the following URL: How should I go about storing and looping through the most recent 24 images for the animation? Is using a MySQL database the best option or are there o ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

At times, the map may only be visible in the top left corner of its designated container

Currently, I am integrating the Google Maps API v3 for JavaScript into my project. However, I am facing an issue where the map only appears in the upper left corner under certain circumstances. To visualize this problem, you can visit this link and click ...

Using a personalized class to bind as a DataSource

Consider the following class: public class Student { private string _name; private int _id; public string Name { // get and set } public int ID { // get and set } } If you want to bind this class to a FormView ...

Unable to modify the state of data in Vue.js

After developing a weather app, I implemented some components with fields in the data section. However, when I changed the value of these fields in the methods section and attempted to access them in another method, I discovered that the old values were be ...

Require a more efficient strategy for iterating through lines of input

One of the challenges I'm facing with my form is that it contains 5 input lines. I need to keep any blank lines that are sandwiched between two filled lines, while removing all others. For instance, if the first line is blank, the second line contains ...

Guide to extracting HTML content from an AJAX call?

I am currently attempting to extract a value from an HTML form. This involves making a GET request to a specific URL, retrieving the HTML content, and then utilizing jQuery to parse through it. Below is the snippet of HTML that I need to navigate through: ...

MembershipCreateStatus.InvalidPassword may occur if a user provides a basic or easily guessed password

Every time I try to get results, it shows as invalidpassword. Even though I am passing Password="mypassword" for all users, it seems to be the default. Membership.CreateUser(Constitid, Password, Email, question, Status, true, out result); Within the web. ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

How to retrieve headers using Express.js middleware

My middleware creates authentication API keys that are then added to the header. const loger = require("easy-loger"); require('dotenv').config(); function authMiddleware(req, res, next){ const appApiKey = process.env.API_KEY; l ...

Tips for customizing bootstrap's fixed navbar-default to ensure that the list items align downwards:

Is it possible to customize the bootstrap fixed navbar-default so that the li elements align downward instead of at the top? If you have any corrections or custom solutions, I'd love to see them! Feel free to share your code on platforms like CodePen, ...

What is the reason for being unable to remove the event listener from a sibling element?

function show1() { console.log("ok1"); document.getElementById("a2").removeEventListener("click", delegate); } function show2() { console.log("ok2"); } function show3() { console.log("ok3"); } function delegate(event) { var flag = event.target ...

Asynchronous Middleware in ExpressJS Routing

I'm having trouble implementing a middleware in Express. Whenever I make a request, I end up with infinite loading times. I've searched on various platforms but couldn't find any examples that utilize an async await middleware stored in a se ...