简体   繁体   中英

How to update the table when same record is inserted using jquery and ajax

I am developing POS application, I am retrieving product after searching the barcode (which is saved in database in product table), there is add Cart button on which I click will add the product details,price and quantity in order table in database and will show after adding to database, if I enter the same product then its price and quantity should be increased.

when I click on add cart for the same product it's retrieving the records from Database with updated quantity and price but it's adding new row instead of updating existing row (because of append) is there any other way which I can create a table so that each time I don't have to append a new row.

相同数量的行添加而不是更新行 The jquery code is

$(document).ready(function(){

$("#submit").click(function(event){
    var barcode=$(this).closest("tr").find("td:nth-child(1)").text();
    var product=$(this).closest("tr").find("td:nth-child(2)").text();
    var price=$(this).closest("tr").find("td:nth-child(3)").text();
    var order={"barcodeid":barcode,"pname":product,"price":price,"qty":1}


    console.log(orderid);
    $.ajax({
        type:'POST',    
        url:'/pos/addproduct',
        dataType: "json",
        data:JSON.stringify(order),
        contentType: "application/json; charset=utf-8",
        success:
            function(data){

            $.each(data,function(index,value){

                var row=$("<tr><td>"+value.oid+"</td>"+"<td>"+value.pname+"</td>"+
                        "<td>"+value.qty+"</td>"+"<td>"+value.price+"</td>"+"<td>"
                        +value.barcodeid+"</td></tr>");
                $("#order").append(row).removeClass("hidden");

            })

        }
    })
});
})

and the order table is

<table id="order" class="hidden" align="center">
<tr>
<th>OrderId</th>
<th>ProductName</th>
<th>Quantity</th>
<th>Price</th>
<th>Barcode</th>
</tr>
<tr >
</table>

First thing I assume your answer from server is a json object giving an orderId (which is unique for the cart, ie it does not change session-wide), then for the required Added product : - its product name - the total price for this product orders only (ie unit price * qty) - the quantity - the barcodeid

I created a jsfiddle to show you my idea : example

it works quite as your own code, except that

  • obviously since I have not your server, I used jsfiddle AJAX service to return what I assume your server returns at POST request
  • as a consequence, server side data are handled through two global variables for orderId, and ordered quantities (for each product, that is why it is an object)
  • in the success function, I look for a cell (td) matching "qty+barcode", if I find it, I update it and the total price cell (which id is "price"+barcode). If I do not find it, I create the row (this is your code) while setting appropriate ids for both quantity and price cells.

    The following snippet in SO does not work (since there is no AJAX service) please run it in the above jsfiddle link

 var qty={}; var orderId = 12; $(document).ready(function() { $("a[id^=submit]").click(function(event){ var barcode=$(this).closest("tr").find("td:nth-child(1)").text(); var product=$(this).closest("tr").find("td:nth-child(2)").text(); var price=$(this).closest("tr").find("td:nth-child(3)").text(); var order={"barcodeid":barcode,"pname":product,"price":price,"qty":1} if (qty.hasOwnProperty(barcode)) { qty[barcode]++; qty[barcode] = 1; } $.ajax({ type:'POST', url:'/echo/json/', dataType: "json", data://JSON.stringify(order), { json: JSON.stringify({ oid: orderId, pname: product, price: parseFloat(price)*qty[barcode], qty:qty[barcode], barcodeid:barcode }), delay: 1 }, contentType: "application/json; charset=utf-8", success:function(data) { value = data var qtyItm = $("#qty"+value.barcodeid); if (qtyItm.length) { qtyItm.html(qty[barcode]); $("#price"+value.barcodeid).html(value.price); } else { var row=$("<tr><td>"+value.oid+"</td>"+"<td>"+value.pname+"</td>"+ "<td id=\\"qty"+value.barcodeid+"\\">"+value.qty+"</td>"+ "<td id=\\"price"+value.barcodeid+"\\">"+value.price+"</td>"+ "<td>"+value.barcodeid+"</td></tr>"); $("#order").append(row).removeClass("hidden"); } }, fail:function() { alert('problem') } }) }); }); 
 table { border: 1px solid black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <table align="center"> <tr><th>Barcode</th><th>ProductName</th><th>Price</th><th>ADD</th></tr> <tr><td>97</td><td>johson</td><td>44.0</td><td><a href="#" id="submit97">Add</a></td></tr> <tr><td>98</td><td>another product</td><td>10.0</td><td><a href="#" id="submit98">Add</a></td></tr> </table> <table id="order" align="center"> <tr><th>OrderId</th><th>ProductName</th><th>Quantity</th><th>Price</th><th>Barcode</th></tr> </table> </body> 

Simple solution will be to create entire Table into JS without much interrupting your code..

JS Code ---

    $(document).ready(function(){

    $("#submit").click(function(event){
        var barcode=$(this).closest("tr").find("td:nth-child(1)").text();
        var product=$(this).closest("tr").find("td:nth-child(2)").text();
        var price=$(this).closest("tr").find("td:nth-child(3)").text();
        var order={"barcodeid":barcode,"pname":product,"price":price,"qty":1}


        console.log(orderid);
        var TableData = "";


         $.ajax({
                type:'POST',    
                url:'/pos/addproduct',
                dataType: "json",
                data:JSON.stringify(order),
                contentType: "application/json; charset=utf-8",
                success:
                    function(data){
TableData = TableData + '<table id="order"  align="center">'
        TableData = TableData + '<tr>';
        TableData = TableData + '<th>OrderId</th>';
        TableData = TableData + '<th>ProductName</th>';
        TableData = TableData + '<th>Quantity</th>';
        TableData = TableData + '<th>Price</th>';
        TableData = TableData + '<th>Barcode</th>';
        TableData = TableData + '</tr>';
                    $.each(data,function(index,value){
                        TableData = TableData + "<tr><td>"+value.oid+"</td><td>"+value.pname+"</td>";
                        TableData = TableData + "<td>"+value.qty+"</td>"+"<td>"+value.price+"</td>";
                        TableData = TableData + "<td>"+value.barcodeid+"</td></tr>";
                    })
 TableData = TableData + '</table>'
                }
            });


        $("#OrderDiv").html("");
        $("#OrderDiv").html(TableData);
});
})

and On HTML Replace

<table id="order" class="hidden" align="center">
<tr>
<th>OrderId</th>
<th>ProductName</th>
<th>Quantity</th>
<th>Price</th>
<th>Barcode</th>
</tr>
<tr >
</table>

With

<div id = 'OrderDiv'> </div>

apply necessary CSS after success Request.

i iterated through all the objects from database and checked whether the id is same as price and barcode if it is same update the price and quantity using their div elements

    function(data){
            $.each(data,function(index,value){
                var temp = "qty" + data[index].barcodeid.trim();
                var qtyitm=$("#"+temp);
                if(qtyitm.length != 0){
                    qtyitm.html(data[index].qty);
                    //("#price"+(data[index].barcodeid.trim())).html(data[index].price);
                    temp = "price" + data[index].barcodeid.trim();
                    qtyitm = $("#"+temp);
                    qtyitm.html(data[index].price);
                }
                else{
                    var row=$("<tr><td>"+data[index].oid+"</td>"+"<td>"+data[index].pname.trim()+
                            "</td>"+
                            "<td id=\"qty"+data[index].barcodeid.trim()+"\">"+data[index].qty+"</td>"+
                            "<td id=\"price"+data[index].barcodeid.trim()+"\">"+data[index].price+"</td>"+
                            "<td>"
                            +data[index].barcodeid.trim()+"</td></tr>");

                    $("#order").append(row).removeClass("hidden");
                    }
            })

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM