Remove duplicate rows in HTML Table after Insert on Button click using jQuery AJAX and Web Service

Last Reply 8 months ago By dharmendr

Posted 8 months ago

i m facing problem with duplicate rows after insert operation in my html table..i bind data with function getdata()...(marked as bind 1 in code). .after insertion ...data is binded using getdata()//(marked as bind 2)..)..but after insertion, repetation of rows occurs.... .ie each row displayed 2 times...but on refreshing page...its gone..when first getdata() is removed ..no preloading of data in table..but data loaded to json table properly after insertion.. i tried windows.load()..but alerts and pop ups not displayed properly..any solution for this...??..

         $(document).ready(function () {
             var id;
             getdata();//bind 1   
             $('#Btnaddstore').click(function () {             
                 var StoreName = $('#TxtStoreame').val();
                 var Storelink = $('#TxtStorelink').val();
                 var byteImage = reader.result;
                 byteImage = byteImage.split(';')[1].replace("base64,", "");
                 var obj = {};
                 obj.Name = StoreName;
                 obj.image = byteImage;
                 if (Name != '') {
                     $.ajax({
                         type: "POST",
                         contentType: "application/json; charset=utf-8",
                         url: "/WebService.asmx/Adddata",                       
                         data: '{data : ' + JSON.stringify(obj) + ' }',
                         dataType: "json",
                         success: function (data) {
                             var obj = data.d;
                             if (obj == 'true') {
			  $('#lblmsg').html("Details Submitted Successfully").fadeOut(2222);
                               getData(); //bind 2                      
                             }
                             if (obj == 'false') {
                                 $('#TxtStoreame').val(''); 
                                 $('#lblmsg').html("name exists").fadeOut(2222);                             
                             }
                         },
                         error: function (result) {
                             alert("Error");                           
                         }
                     });
                 }
                 else {
                     alert('Please enter all the fields')
                     return false;
                 }
             })  
         });
         function getdata() {
             $.ajax({
                 type: "POST",
                 contentType: "application/json; charset=utf-8",
                 url: "/WebService.asmx/Getdata",
                 data: {},
                 dataType: "json",
                 success: function (data) {
                   //  $('#dataTables-example tbody').remove();
                     //console.log(data.d);
                     var table = $('#dataTables-example');
                     var rows = "";
                     for (var i = 0; i < data.d.length; i++) {
                         var ID = data.d[i].ID;
                         var Name = data.d[i].Name;
                              var image = '<img class=imgstore width=100px height=100px, src="data:image/jpg;base64,' + data.d[i].image + '" />'
                              rows += "<tr><td>" + ID + "</td><td>" + Name + "</td><td>" + image + "</td>";
                              }
                     table.append(rows);
                 },
                 error: function () {
                     alert("Error while Showing update data");
                 }
             });
         }     

 

You are viewing reply posted by: dharmendr 8 months ago.
Posted 8 months ago

Hi jovceka,

Check this example. Now please take its reference and correct your code.

Database

I have made use of the following table Customers with the schema as follows.

I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file

HTML

<table id="example">
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Country</th>
    </tr>
</table>
<br />
<br />
<table>
    <tr>
        <td>Name</td>
        <td><input type="text" id="txtName" /></td>
    </tr>
    <tr>
        <td>Country</td>
        <td><input type="text" id="txtCountry" /></td>
    </tr>
    <tr>
        <td colspan="2"><input type="button" value="Insert" id="btnAdd" /></td>
    </tr>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        GetProduct();
        $('#btnAdd').click(function () {
            var obj = {};
            obj.Name = $('#txtName').val();
            obj.Country = $('#txtCountry').val();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/AddCustomer",
                dataType: "json",
                data: JSON.stringify(obj),
                success: function (data) {
                    if (data.d == 'true') {
                        GetProduct();
                    }
                    else {
                        $('#txtName').val() = "";
                        $('#txtCountry').val() = "";
                    }
                },
                error: function (result) {
                    alert("Error");
                }
            });
        })
    });
    function GetProduct() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebService.asmx/GetData",
            data: {},
            dataType: "json",
            success: function (data) {
                var table = $('#example');
                $(table).find("tr:gt(0)").remove();
                var rows = "";
                for (var i = 0; i < data.d.length; i++) {
                    var id = data.d[i].Id;
                    var name = data.d[i].Name;
                    var country = data.d[i].Country;
                    rows += "<tr><td>" + id + "</td><td>" + name + "</td><td>" + country + "</td></tr>";
                }
                table.append(rows);
            },
            error: function (response) {
                alert("Error while Showing update data");
            }
        });
    }
</script>

Namespaces

C#

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

VB.Net

Imports System
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Services

WebService

C#

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public List<Customer> GetData()
{
    List<Customer> customers = new List<Customer>();
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT CustomerId,Name,Country FROM Customers";
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        cmd.Connection = con;
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            customers.Add(new Customer
            {
                Id = Convert.ToInt32(sdr["CustomerId"]),
                Name = sdr["Name"].ToString(),
                Country = sdr["Country"].ToString()
            });
        }
        con.Close();
    }

    return customers;
}

[WebMethod]
public string AddCustomer(string Name, string Country)
{
    string status = "";
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "INSERT INTO Customers VALUES(@Name,@Country)";
    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand(query);
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@Name", Name);
        cmd.Parameters.AddWithValue("@Country", Country);
        con.Open();
        status = cmd.ExecuteNonQuery() > 0 ? "true" : "false";
        con.Close();
    }
    return status;
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

VB.Net

<WebService([Namespace]:="http://tempuri.org/")>
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<System.Web.Script.Services.ScriptService>
Public Class WebService
    Inherits System.Web.Services.WebService

    <WebMethod>
    Public Function GetData() As List(Of Customer)
        Dim customers As List(Of Customer) = New List(Of Customer)()
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT CustomerId,Name,Country FROM Customers"
        Dim cmd As SqlCommand = New SqlCommand(query)
        Using con As SqlConnection = New SqlConnection(conString)
            cmd.Connection = con
            con.Open()
            Dim sdr As SqlDataReader = cmd.ExecuteReader()

            While sdr.Read()
                customers.Add(New Customer With {
                    .Id = Convert.ToInt32(sdr("CustomerId")),
                    .Name = sdr("Name").ToString(),
                    .Country = sdr("Country").ToString()
                })
            End While

            con.Close()
        End Using

        Return customers
    End Function

    <WebMethod>
    Public Function AddCustomer(ByVal Name As String, ByVal Country As String) As String
        Dim status As String = ""
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "INSERT INTO Customers VALUES(@Name,@Country)"
        Using con As SqlConnection = New SqlConnection(conString)
            Dim cmd As SqlCommand = New SqlCommand(query)
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@Name", Name)
            cmd.Parameters.AddWithValue("@Country", Country)
            con.Open()
            status = If(cmd.ExecuteNonQuery() > 0, "true", "false")
            con.Close()
        End Using

        Return status
    End Function

    Public Class Customer
        Public Property Id As Integer
        Public Property Name As String
        Public Property Country As String
    End Class
End Class

Screenshot