Treating logic and exceptions - jQuery

Asked

Viewed 83 times

2

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

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>

Code for Ajax requests:

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 treat 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 respect to refresh the page I do not know how to proceed to fix it. I think the correct thing to do is in updating the page it remove the product that was added according to the buy button, from your id.

  • 2

    You have spent 80% of your text describing a situation that has no relevance to the problem. And the problem is poorly explained. Please be succinct and clear.

  • @Brunnovianna I updated the question, now being clearer and explaining more the problem.

  • Why do you need to re-load the page? Since you are using Ajax, it would not be easier to remove the "buy" button and related item with jQuery .remove()?

  • @Dvdsamm Yes, or on the page update, the clicked item would come with the active remove button, not buy it, which would be what I would need in case.

  • So if you delete the reloads from the code does not work?

  • @Dvdsamm Works, however I wanted that type, the buy button was clicked, then it is "replaced" by the remove. If the page is updated, it comes as buy again, but I would need it in case it came as remove.

  • Now I get it. The case is this: when the person clicks on buying, you need to store this information somewhere, so when the page is loaded again, pull this information and make the comparison. I don’t know how you’re doing this "guard" of information. If it is in the bank, you should pull it from the bank and see if the item that was "purchased" is there, and if it is, vc display the "remove" button instead of the "buy".

  • @Dvdsamm That would be exactly what you said, but I’m having trouble "keeping" this information, because I don’t know how I should proceed to do the same.

Show 4 more comments

1 answer

0


The solution I found long after was loading the page is made a request ajax to be able to check if there is product added and the return value of the request is added in two input of the kind hidden, to take 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" />

Requisition 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=''}}";
            }
        });
    })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.