Handling Logic and Exections - jQuery

2

I have some buttons which in onclick of them work with two Ajax requests for an external file that add products, but this is not of extreme importance in this matter. My problem is this: if the buy button is clicked, the product is added, but if the page is updated it will be there, but I can only have one product the same at a time and if after the updated page the button buy is clicked again, another product is added and this can not happen, because what is already added must be removed from the removeCartaotoCart function so that the new one is added so that I have only one product at a time. p>

Button code:

 <button type="button" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Comprar</span></span></button>
 <button style="display: none;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remover</span></span></button>

Ajax Requests Code:

var productSelected = "";
            function addCartao(product_id){
                if( productSelected != "" ){
                    removeCartaotoCart(productSelected);    // Remove the item in cart, if there is one.
                  }
                $j('#cartaoMensagem'+product_id).hide();
                $j('#cartaoMensagemRemover'+product_id).show();
                $j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
                $j.ajax({
                  type: "POST",
                  url: "adiciona.php",
                  data: {
                    product_id: product_id
                  },
                  dataType: 'json',
                  cache : false,
                  beforeSend: function () {

                  },
                  success: function (retorno) {
                    var button = $j('#cartaoMensagemRemover'+product_id);
                    productSelected = product_id;  
                    $j('.item-custom').append('<tr id="trAppend'+product_id+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
                    getSubTotal();
                    getGrandTotal();
                  },
                  complete: function () {

                  },
                  error: function (x,y,z) {
                    alert("error");
                    alert(x);
                    alert(y);
                    alert(z);
                    window.location.reload();
                    history.go(0);
                    window.location.href=window.location.href;
                  }
              });
            }

            function removeCartaotoCart(itemId){
                productSelected = ""; 
                $j('#cartaoMensagemRemover'+itemId).hide();
                $j('#cartaoMensagem'+itemId).show();
                $j.ajax({
                    type:"POST",
                    url:"remove.php",
                    data:{
                        itemId: itemId
                    },
                    cache: false,
                    beforeSend: function(){

                    },
                    success: function(retorno){
                        var button = $j('#cartaoMensagemRemover'+itemId);
                        $j('.item-custom #trAppend'+itemId+'').remove();
                        getSubTotal();
                        getGrandTotal();

                    },
                    complete: function () {

                    },
                    error: function (x,y,z) {
                    alert("error");
                    alert(x);
                    alert(y);
                    alert(z);
                    window.location.reload();
                    history.go(0);
                    window.location.href=window.location.href;
                  }
                });
            }

Note: From the variable productSelected , I can handle an exception: if the buy button is clicked and there is already a product added, it is removed for the new one to be added, but this other exception with Regarding updating the page I do not know how to proceed to solve it. I think the correct thing to do is in the update of the page he removes the product that was added according to the buy button, from his id

    
asked by anonymous 05.09.2017 / 20:48

1 answer

0

The solution that I found a lot of time later was in loading the page a ajax request is made to check if there is added product and the return value of the request is added in two input of type hidden to get this value and make the request that removes the product.

Code of input's :

<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="0" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id" value="0" />

Request code Ajax :

$j(document).ready(function(){
        //Requisição Ajax para ver se existe produtos na atualização da página
        $j.ajax({
            type: "POST",
            url: "verifica.php",
            data:{

            },
            dataType: 'json',
            cache: false,
            beforeSend: function(){
            },
            success: function(retorno){
                $j('#cartao_adicionado').attr('value', retorno['adicionado']) ;
                $j('#cartao_adicionado_product_id').attr('value', retorno['id_produto']);
                isCartaoAdicionado = $j('#cartao_adicionado').val();
                isCartaoAdicionadoProductId = $j('#cartao_adicionado_product_id').val();
                removeCartaotoCart(isCartaoAdicionadoProductId); //chama a requisição para remove o produto a partir do seu id.
            },
            complete: function(){

            },
            error: function(x,y,z){
                alert(x);
                alert(y);
                alert(z);
                alert("Erro!");
                window.location.reload();
                history.go(0);
                window.location.href = "{{store url=''}}";
            }
        });
    })
    
14.11.2017 / 18:23