6
Context
I am trying to make the persistence in the database of a purchase as well as all of its items. For this I am using a file .jsp
. But I need to send the data from a web page. The purchase data is easy. The problem is in the same items, I wanted to do something dynamic, letting the user enter as many items as necessary. But I came across a logic error that I am not able to solve: In the Onchange event of the barcode input, I perform an Ajax request that goes to the database, selects the product that has that barcode and returns the entire object. In doing so, I need to insert it into an array of Javascript objects, but at this point comes my problem.
Problem
I cannot define a dynamic object, when I update the attributes of the object coming with the data from Ajax, and 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 would be most 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!");
}
});
mrlew, THANK YOU VERY MUCH! IT HELPED ME A LOT, that’s right, I knew I was with the same object, but I didn’t know how to change it! It really helped me a lot! I thought I would have to modify the whole architecture of my logic! How do I give you the highest score on this Forum? I’m new here too! Thanks, success!!!
– Matheus Minguini
+1 for the good answer. @Matheusminguini .
– Wilker
Okay, thanks, guys! You guys are awesome!
– Matheus Minguini
@Matheusminguini thanks rsrs that good it worked. Good luck on the project!
– mrlew
@Thank you Wilker! Hugs!
– mrlew