mercredi 31 décembre 2014

Problems with ajax and session variable in Web2Py


I'm developing an app in Web2Py that consists in a little e-commerce. Have a controller and page that the link is localhost:8000/topranchos/produto, with products, were topranchos is the app.


In the page produto there are a list of products like this:


The image is in this link


When the button "Adicionar ao carrinho" is clicked, the javascript function is executed:



<script>
function adicionarCarrinho(prod, qtde) {
quantidade = document.querySelector(qtde).value
console.log(quantidade)
if(quantidade > 0) {
$.get("{{=URL(f="adicionarCarrinho")}}", {produto: prod, qtde: quantidade} )
.done(function( data ) {
console.log (data)
var atual =document.querySelector(".badge-carrinho").innerHTML;
document.querySelector(".badge-carrinho").innerHTML =
parseInt(quantidade) + parseInt(atual);
alert("Adicionado ao carrinho com sucesso");
});
}
else alert("Selecione a quantidade de itens deste produto que você deseja");
}
</script>


It's make a requisition to the action default/adicionarCarrinho:



def adicionarCarrinho():
if request.vars:
session.carrinho.append(
#{'produto':db(db.produto.id == request.vars['produto']).select(),
{'produto':int(request.vars['produto']),
'quantidade':int(request.vars['qtde'])}
)
print "----------"
print session.carrinho
return str("OK")


Where session.carrinho have a list that was declared on db.py model:



#carrinho
session.carrinho = []


On the terminal, the command print session.carrinho print the item received by the ajax request, but when I add other itens the list is empty. When I click on the page of carrinho, that shows the session.carrinho's informations, the var is empty.


How can I repair this? I tried use cookies of course Web2Py book, but I dummie on Web2Py and not has success yet :/


thank you!





Aucun commentaire:

Enregistrer un commentaire