Context
I'm trying to persist in the database of a purchase, as well as all of its items. For this I am using a .jsp
file. But I need to send the web page data. Purchasing data is easy. The problem is in the items of the same, I wanted to do something dynamic, letting the user insert as many items as needed. But I came across a logic error that I'm not sure how to solve: In the OnChange event of the barcode input, I perform an Ajax request that goes to the Database, selects the product that owns that Barcode, and returns the its entire object. When doing this, I need to insert the same into an array of Javascript objects, however, at that point comes my problem.
Problem
I can not define a dynamic object, when I update the attributes of the object coming with the Ajax data, and I insert in the Array, if the user wants a new object (Product), it overwrites the same object, so I have several objects within the Array, with the same values. If you can or will try to help me, I will be extremely grateful.
JS code
$("#cbarras").on('change', function() {
var cbarras = $('#cbarras').val();
var cliente = $('#cliente').val();
var data = $('#data_compra').val();
var quantidade = $('#quantidade').val();
if (cbarras && cliente && data && quantidade){
$.ajax({
url : "http://localhost:8080/ProjBiltiful/BuscarProduto.jsp?id=" + cbarras,
dataType : "json",
success : function(data){
if (data){
var total_item = data.vvenda * quantidade;
total += total_item;
$('#total_venda').val(total);
//INCLUO OS ITENS DA VENDA EM UM ARRAY DE OBJETOS
obj_itens.cbarras = data.cbarras;
obj_itens.valor = data.vvenda;
obj_itens.qtd = quantidade;
obj_itens.total = total_item;
itens_venda.push(obj_itens);
obj_itens.cbarras = 0;
obj_itens.valor = data.vvenda;
obj_itens.qtd = 0;
obj_itens.total = 0;
console.log(itens_venda);
$('#table_itens tbody').append(
'<tr class="child">'
+ '<td align="center">' + data.cbarras + '</td>'
+ '<td align="center">' + data.nome + '</td>'
+ '<td align="center">' + data.vvenda + '</td>'
+ '<td align="center">' + quantidade + '</td>'
+ '<td align="center">' + total_item + '</td>' +
'</tr>'
);
} else {
alert('Produto não encontrado !');
}
},
error: function(err){
alert('Ooops... Encontramos um erro ao buscar o produto');
}
});
} else {
alert("Você deve ter esquecido de preencher algum campo da venda!");
}
});