Error: Authentication failed during jQuery Ajax call in ASP.Net

Last Reply 2 months ago By nauna

Posted 2 months ago

hi,

 

i am using on scroll page loading solution of mudassir but it is not working well. instead of showign next data, it is repeating only 1 record

 

here is my code please advice what is wrong.

ALTER PROCEDURE [dbo].[GetCustomersPageWise]
      @PageIndex INT = 1
      ,@PageSize INT = 10
      ,@PageCount INT OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
            (
                  ORDER BY [CountryId] ASC
            )AS RowNumber
      ,[CountryId]
      ,[CountryName]
     
    INTO #Results
      FROM [Country]
     
      DECLARE @RecordCount INT
      SELECT @RecordCount = COUNT(*) FROM #Results
 
      SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@PageSize AS DECIMAL(10, 2)))
      PRINT       @PageCount
           
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
     
      DROP TABLE #Results
END

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    var pageIndex = 1;
    var pageCount;
    $(window).scroll(function () {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            GetRecords();
        }
    });
    function GetRecords() {
        pageIndex++;
        if (pageIndex == 2 || pageIndex <= pageCount) {
            $("#loader").show();
            $.ajax({
                type: "POST",
                url: "Default.aspx/GetCustomers",
                data: '{pageIndex: ' + pageIndex + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        }
    }
    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
        var customers = xml.find("Customer");
        customers.each(function () {
            var customer = $(this);
            var table = $("#dvCustomers table").eq(0).clone(true);
            $(".id", table).html(customer.find("CountryId").text());
            $(".name", table).html(customer.find("CountryName").text());
           
            $("#dvCustomers").append(table).append("<br />");
        });
        $("#loader").hide();
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
   <table>
<tr>
    <td>
    <div id="dvCustomers">
        <asp:Repeater ID="rptCustomers" runat="server">
            <ItemTemplate>
                <table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
                border: dashed 2px #04AFEF; background-color: #B0E2F5">
                <tr>
                    <td>
                        
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>CountryID: </b><span class="city"><%# Eval("CountryId") %></span><br />
                        <b>CountryName: </b><span class="postal"><%# Eval("CountryName") %></span><br />
                     
                    </td>
                </tr>
            </table>
            <br />
            </ItemTemplate>
        </asp:Repeater>
    </div>
</td>
<td valign="bottom">
    <img id="loader" alt="" src="loading.gif" style="display: none" />
</td>
</tr>
</table>
    </form>
</body>
</html>

 

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rptCustomers.DataSource = GetCustomersData(1);
            rptCustomers.DataBind();
        }
    }

    public static DataSet GetCustomersData(int pageIndex)
    {
        string query = "[GetCustomersPageWise]";
        SqlCommand cmd = new SqlCommand(query);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
        cmd.Parameters.AddWithValue("@PageSize", 10);
        cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
        return GetData(cmd);
    }

    private static DataSet GetData(SqlCommand cmd)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds, "Customer");
                    DataTable dt = new DataTable("PageCount");
                    dt.Columns.Add("PageCount");
                    dt.Rows.Add();
                    dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value;
                    ds.Tables.Add(dt);
                    return ds;
                }
            }
        }
    }

    [WebMethod]
    public static string GetCustomers(int pageIndex)
    {
        return GetCustomersData(pageIndex).GetXml();
    }
}

 

Posted 2 months ago

Hi nauna,

The problem is due to authentication failed.

So you have to follow the below instruction.

Also i have created sample as per your code and its working without no issue.

In your App_Code folder, with in your RouteConfig.cs comment out the following line or change its RedirectMode to Off.

public static void RegisterRoutes(RouteCollection routes)
{
    var settings = new FriendlyUrlSettings();
    //settings.AutoRedirectMode = RedirectMode.Permanent;
    settings.AutoRedirectMode = RedirectMode.Off;
    routes.EnableFriendlyUrls(settings);
}

Below is the working sample.

SQL

ALTER PROCEDURE [dbo].[GetCustomersPageWise]
      @PageIndex INT = 1
      ,@PageSize INT = 10
      ,@PageCount INT OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
            (
                  ORDER BY [CustomerID] ASC
            )AS RowNumber
      ,[CustomerID]
      ,[ContactName]
      
    INTO #Results
      FROM [Customers]
      
      DECLARE @RecordCount INT
      SELECT @RecordCount = COUNT(*) FROM #Results
  
      SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@PageSize AS DECIMAL(10, 2)))
      PRINT       @PageCount
            
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
      
      DROP TABLE #Results
END

HTML

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        var pageIndex = 1;
        var pageCount;
        $(window).scroll(function () {
            if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                GetRecords();
            }
        });
        function GetRecords() {
            pageIndex++;
            if (pageIndex == 2 || pageIndex <= pageCount) {
                $("#loader").show();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetCustomers",
                    data: '{pageIndex: ' + pageIndex + '}',
                    contentType: "application/json",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
            }
        }
        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
            var customers = xml.find("Customer");
            customers.each(function () {
                var customer = $(this);
                var table = $("#dvCustomers table").eq(0).clone(true);
                $(".id", table).html(customer.find("CustomerID").text());
                $(".name", table).html(customer.find("ContactName").text());

                $("#dvCustomers").append(table).append("<br />");
            });
            $("#loader").hide();
        }
    </script>
    <table>
        <tr>
            <td>
                <div id="dvCustomers">
                    <asp:Repeater ID="rptCustomers" runat="server">
                        <ItemTemplate>
                            <table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px; border: dashed 2px #04AFEF; background-color: #B0E2F5">
                                <tr>
                                    <td></td>
                                </tr>
                                <tr>
                                    <td>
                                        <b>CountryID: </b><span class="city"><%# Eval("CustomerID") %></span><br />
                                        <b>CountryName: </b><span class="postal"><%# Eval("ContactName") %></span>

                                    </td>
                                </tr>
                            </table>
                            <br />
                        </ItemTemplate>
                    </asp:Repeater>
                </div>
            </td>
            <td valign="bottom">
                <img id="loader" alt="" src="loading.gif" style="display: none" />
            </td>
        </tr>
    </table>
</asp:Content>

C#

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.UI;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            rptCustomers.DataSource = GetCustomersData(1);
            rptCustomers.DataBind();
        }
    }

    public static DataSet GetCustomersData(int pageIndex)
    {
        string query = "[GetCustomersPageWise]";
        SqlCommand cmd = new SqlCommand(query);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
        cmd.Parameters.AddWithValue("@PageSize", 10);
        cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
        return GetData(cmd);
    }

    private static DataSet GetData(SqlCommand cmd)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds, "Customer");
                    DataTable dt = new DataTable("PageCount");
                    dt.Columns.Add("PageCount");
                    dt.Rows.Add();
                    dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value;
                    ds.Tables.Add(dt);
                    return ds;
                }
            }
        }
    }

    [WebMethod]
    public static string GetCustomers(int pageIndex)
    {
        return GetCustomersData(pageIndex).GetXml();
    }
}

Also you can use resolve url like below.

url: '<%=ResolveUrl("Default.aspx/GetCustomers") %>',

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html