[Solved] Records duplicating after adding in HTML Table using jQuery AJAX in ASP.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

here partial page refresh not working with server side page scroll for json ajax table when new data added to table.

i can make full page refresh with location.reload(true).

but Productbypage(currentPage) not working for partial refresh.

i mean adding Productbypage(currentPage) in success function for partial page updation.

any option to replace update panel with Productbypage(currentPage)?

     <script type="text/javascript"> 
         $(document).ready(function () {
             var currentPage = 1;
             Productbypage(currentPage);
             $(window).scroll(function () {
                 if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                     currentPage += 1;
                     Productbypage(currentPage);
                 }
             });
            $("#BtnaddProduct").click(function () {
                                
                 var ProdDetails = $('#TxtPdtdetail').val();
                 var OldPrice = $('#TxtoldOffprice').val();
                 var CurrentPrice = $('#TxtPdtCrrprice').val();
                 var OffDetails = $('#TxtPdtOffDetails').val();
                 var obj = {};
                 obj.OldPrice = OldPrice;
                 obj.CurrentPrice = CurrentPrice;
                 obj.OffDetails = OffDetails;
                 obj.ProdDetails = ProdDetails;
               
                 $.ajax({
                     type: "POST",
                     url: "/WebService.asmx/AddProduct",
                     data: '{data : ' + JSON.stringify(obj) + ' }',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function (data) {
                         alert("success");
                         Productbypage(currentPage);
 
                         // location.reload(true);here full page is reloading ,insteading of reloading the particular part(partial page refresh)..i.e.Productbypage()
                         
                     },
                     error: function (r) {
                         alert("failure");
                     },
                    
                 });
                 return false;
                 
             });
                       });
         function Productbypage(currentPageNumber) {
             $.ajax({
                
                // contentType: "application/json; charset=utf-8",
                 url: "/WebService.asmx/Productbypage",
                 method: 'post',
                 dataType: "json",
                 async: false,
                 data: { pageNumber: currentPageNumber, pageSize: 5 },
           
                 success: function (data) {
                 //  $('#dataTables-example tbody').remove();

                     var table = $('#Tables-example');
                    
                     var rows = "";
                     
                     //for (var i = 0; i < data.d.length; i++)
                     $(data).each(function (index, emp) {
                      //{
                        
                        
                         var Proddetails = emp.Proddetails;
                         var OldPrice = emp.OldPrice;
                         var CurrentPrice = emp.CurrentPrice;
                         var OffDetails = emp.OffDetails;
                      
                         rows += "<tr><td>" + Proddetails + "</td><td>" + OldPrice + "</td><td>" + CurrentPrice + "</td><td>" + OffDetails + "</td></tr>";
                          
                     });
                      table.append(rows);
                     
                 },
                 error: function () {
                     alert("Error while Showing update data");
                 }
             });
         } 
     </script>

 

Posted 4 months ago

Hi jovceka,

Make the table empty before adding record to it.

$('#Tables-example').empty();

Refer below sample.

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" src="http://cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var currentPage = 1;
            Productbypage(currentPage);
            $(window).scroll(function () {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    currentPage += 1;
                    Productbypage(currentPage);
                }
            });
            $("#BtnaddProduct").click(function () {
                var ProdDetails = $('#TxtPdtdetail').val();
                var OldPrice = $('#TxtoldOffprice').val();
                var CurrentPrice = $('#TxtPdtCrrprice').val();
                var OffDetails = $('#TxtPdtOffDetails').val();
                var obj = {};
                obj.OldPrice = OldPrice;
                obj.CurrentPrice = CurrentPrice;
                obj.OffDetails = OffDetails;
                obj.ProdDetails = ProdDetails;
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/AddProduct",
                    data: '{data : ' + JSON.stringify(obj) + ' }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert("success");
                        Productbypage(currentPage);
                    },
                    error: function (r) {
                        alert("failure");
                    }
                });
                return false;
            });
        });
        function Productbypage(currentPageNumber) {
            var obj = {};
            obj.pageNumber = currentPageNumber;
            obj.pageSize = 5;
            $.ajax({
                type: "POST",
                url: "WebService.asmx/Productbypage",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var table = $('#Tables-example');
                    $('#Tables-example').empty();
                    var rows = "";
                    $(r.d).each(function (index, emp) {
                        var Proddetails = emp.Proddetails;
                        var OldPrice = emp.OldPrice;
                        var CurrentPrice = emp.CurrentPrice;
                        var OffDetails = emp.OffDetails;
                        rows += "<tr><td>" + Proddetails + "</td><td>" + OldPrice + "</td><td>" + CurrentPrice + "</td><td>" + OffDetails + "</td></tr>";
                    });
                    table.append(rows);
                },
                error: function (r) {
                    alert("Error while Showing update data");
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div class="row">
        <div class="col-lg-12">
            <div class="col-lg-12">
                <div class="panel panel-custom-horrible">
                    <div class="panel panel-heading">
                        <h3 class="panel-title">
                            <i class="fa fa-bar-chart-o"></i>Add Products</h3>
                    </div>
                    <div class="panel panel-body">
                        <div class="form-group col-lg-4">
                            <label>
                                Old price</label>
                            <input type="text" name="Old Off" id="TxtoldOffprice" class="form-control" placeholder="Old price"
                                required="" />
                        </div>
                        <div class="form-group col-lg-4">
                            <label>
                                current price</label>
                            <input type="text" name="current OFF" id="TxtPdtCrrprice" class="form-control" placeholder="current price"
                                required="" />
                        </div>
                        <div class="form-group col-lg-4">
                            <label>
                                Off Details</label>
                            <input type="text" name="off details" id="TxtPdtOffDetails" class="form-control"
                                placeholder="off details like percentage off" required="" />
                        </div>
                        <div class="form-group col-lg-8">
                            <label>
                                product details</label>
                            <textarea class="form-control" rows="3" id="TxtPdtdetail"></textarea>
                            <div class="form-group col-lg-8">
                                <div style="float: right">
                                    <button class="btn btn-large btn-primary" type="button" id="BtnaddProduct">
                                        Submit</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-lg-12">
                    <div class="panel panel-custom-horrible custhead">
                        <div class="panel panel-heading">
                            Product details
                        </div>
                        <div class="panel-body">
                            <div class="dataTable_wrapper">
                                <div id="Tables-example_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
                                    <div class="row">
                                        <div class="table-responsive" id="tableproduct">
                                            <table id="Tables-example" class="table table-responsive table-striped table-bordered table-hover dataTable no-footer storetable"
                                                role="grid" aria-describedby="dataTables-example_info">
                                                <thead>
                                                    <tr role="row" class="srow">
                                                        <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1"
                                                            style="width: 110px;" aria-label="CSS grade: activate to sort column ascending">
                                                            Product Details
                                                        </th>
                                                        <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1"
                                                            style="width: 110px;" aria-label="CSS grade: activate to sort column ascending">
                                                            Old price
                                                        </th>
                                                        <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1"
                                                            style="width: 110px;" aria-label="CSS grade: activate to sort column ascending">
                                                            Current price
                                                        </th>
                                                        <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1"
                                                            style="width: 110px;" aria-label="CSS grade: activate to sort column ascending">
                                                            Off Details
                                                        </th>
                                                    </tr>
                                                </thead>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
</body>
</html>

Code

C#

WebService.cs

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [System.Web.Services.WebMethod]
    public string AddProduct(Products data)
    {
        string message = string.Empty;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            SqlCommand cmd = new SqlCommand("sp_AddProduct");
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Proddetails", data.Proddetails);
            cmd.Parameters.AddWithValue("@OldPrice", data.OldPrice);
            cmd.Parameters.AddWithValue("@CurrentPrice", data.CurrentPrice);
            cmd.Parameters.AddWithValue("@OffDetails", data.OffDetails);
            cmd.Connection = con;
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
            if (i == 1)
            {
                message = "true";
            }
            else
            {
                message = "false";
            }
            con.Close();
            return message;
        }
    }

    [System.Web.Services.WebMethod]
    public Array Productbypage(int pageNumber, int pageSize)
    {
        List<Products> details = new List<Products>();
        string cs = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("sp_pdt_page", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@PageNumber",
                Value = pageNumber
            });
            cmd.Parameters.Add(new SqlParameter()
            {
                ParameterName = "@PageSize",
                Value = pageSize
            });
            using (var sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                DataTable TableData = new DataTable();
                TableData.Clear();
                sda.Fill(TableData);
                foreach (DataRow dtrow in TableData.Rows)
                {
                    Products user = new Products();
                    user.Productid = Convert.ToInt32(dtrow["Productid"].ToString());
                    user.Proddetails = dtrow["Proddetails"].ToString();
                    user.OldPrice = dtrow["OldPrice"].ToString();
                    user.CurrentPrice = dtrow["CurrentPrice"].ToString();
                    user.OffDetails = dtrow["OffDetails"].ToString();
                    details.Add(user);
                }
            }
        }
        return details.ToArray();
    }

    public class Products
    {
        public int Productid;
        public string Proddetails;
        public string OldPrice;
        public string CurrentPrice;
        public string OffDetails;
    }
}