1

I got a foreach loop for my itens in my cart. So when i click in my plus or remove buttons, my $value updates fine. But im getting double value in each row.

here is my script.

<script type="text/javascript">
   var multi = $('.output');
       $.each(multi,function () {
       $('.btn').on('click', function() {
       $('.wr').load('  .output'); 
         });
       });


    </script>

and inside of my php foreach loop i have this.

<td class="wr"><div class="output">'.$value.'</div></td>

All i want is to update only that div when i click in my btn classes.

my btns

$btn_add    ='<a class="btn btn-success actions plus" data_action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
$btn_remove ='<a class="btn btn-warning actions less" data_action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';

look this pic to understand whats going on...enter image description here

how can i solve this?

My cart.php where is my foreach loop...

    function cart()
    {
      global $conn;
      $fabric_options = '';
      $query2 = "SELECT * FROM almofadas";
      $result = mysqli_query($conn,$query2);

      while($rows = mysqli_fetch_assoc($result))
      {
        $tecido=$rows['tecido'];
        $id_price=$rows['id_price'];
        $fabric_options .= "<option value=''.$id_price.''>{$rows['tecido']}</option>";
      }

      foreach ($_SESSION as $name => $value)
      {
        if($value > 0)
        {
          if(substr($name, 0, 8 ) == "product_")
          {
            $length = strlen($name) -8;
            $item_id = substr($name,8 , $length);

            $query = "SELECT * 
              FROM gallery2 
              WHERE gallery2.id =".escape_string($item_id). "";
            $run_item = mysqli_query($conn,$query);

            echo $value."</br>"; // this is echoing my values in the header

            while($rows = mysqli_fetch_assoc($run_item))
            { 
              $vari   = $rows['variante'];
              $num    = $rows['title'];
              $id     = $rows['id'];
              $btn_add ='<a class="btn btn-success actions plus" data_action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></a>';
              $btn_remove ='<a class="btn btn-warning actions less" data_action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></a>';
              $btn_delete ='<a class="btn btn-default actions" data_action="delete" product_id="'.$id.'" onclick="deleteRow(this)"><i class="fa fa-times fa-lg" aria-hidden="true"></i></a>';

              if($rows['variante'] < 1)
              {
                $vari="";
              }else{
                $vari = "-".$rows['variante'];
              }

              $product = '
              <td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
              <td>'.$num.''.$vari.'</td>
              <td style="width:15%;">
               <select id="fabric" class="select form-control selectpicker" required="" onchange="saveChoice()" >
                '. $fabric_options . '  
               </select>
              </td>
              <td>
               <select  id="size" class="select form-control selectpicker" required style="width:80%;" onchange="saveChoice()" >
               <option value="50">50x50</option>
               <option value="40">45x45</option>
               </select>
              </td>
              <td class="wr"><div class="output" value="'.$value.'">'.$value.'</div></td>
              <td>R$</td>
              <td>sub.total</td>
              <td> 
               '.$btn_add.' '.$btn_remove.' '.$btn_delete.'
              </td>
              </tr>';

              echo $product;
            } 
          }
        }
      }
    }

this handles my buttons functionality. cart_functions.php...

<?php header('Content-Type: application/json');

if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $prod   = $_GET['prod_id'];
    switch ($action) {
        case 'add':
            echo add_prod($prod);
        break;
        case 'plus':
            echo plus_prod($prod);
        break;
        case 'remove':
            echo remove_prod($prod);
        break;
        case 'delete':
            echo delete_prod($prod);
        break;
        default:
            echo json_encode(['error'=>'error']);
        break;
    }
}

function add_prod($item){
    //sua função para add
 return json_encode(['add'=>'success']);
}
function plus_prod($item){

      if(isset($_GET['prod_id'])){
    $_SESSION['product_'.$_GET['prod_id']]+=1;

    if($_SESSION['product_'.$_GET['prod_id']] < 1){
           return json_encode(['plus'=>'success']);

    }else{
        return json_encode(['plus'=>'success']);
             }
    }

}
function remove_prod($item){
    //sua função para remove
    $_SESSION['product_'.$_GET['prod_id']]--;
if($_SESSION['product_'.$_GET['prod_id']] < 1){
    return json_encode(['remove'=>'success']);
}
}


function delete_prod($item){
    //sua função para delete
    $_SESSION['product_'.$_GET['prod_id']]= '0';
    return json_encode(['delete'=>'success']);
}

?>

All this is rendered in my checkout.php

<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo "Galeria página  ". $page ?></title>
<link rel="stylesheet" href="../../css/bootstrap.min.css">
<link rel="stylesheet" href="../../css/custom_nav.css">
<link href="../../css/gallery.css" rel="stylesheet">

<link rel="stylesheet" href="../../css/carousel.css">

<link href="gallery_includes/fullscreenstyle.css" type="text/css" rel="stylesheet">
</link>
<link href="gallery_includes/pagestyle.css" type="text/css" rel="stylesheet">
</link>
<link href="../css/modal_drop.css" type="text/css" rel="stylesheet">
<!--<link href="../../css/megadrop.css" type="text/css" rel="stylesheet">-->
</link>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">

<!--script src="../../js/carousel.js" type="text/javascript"></script-->
<link href="../../font-awesome-4.3.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto|Titillium+Web" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<style>
.hide-bullets {
list-style:none;
margin-left: -40px;
margin-top:20px;
}
</style>

    <header>

        <nav class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
                    <div class="navbar-header">
                      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                      </button>
                      <a class="navbar-brand" href="#">Lista</a>
                    </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
               <li class=""><a href="index.php" onClick="history.go(0)" VALUE="Refresh">Início <span class="sr-only"></span></a></li>
                <!--<li><a href="#">Nao definido</a></li>-->

                  </ul>
                </li>
              </ul>
              <!--<form class="navbar-form navbar-left"  action="search.php" role="form">
                <div class="form-group">
                   <input type="search" name="search" class="form-control" placeholder="Procurar">
                   <button name="search_submit" class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i> Pesquisar</button>
                </div>

              </form>-->
              <ul class="nav navbar-nav navbar-right">
              <li><a href="../checkout.php"><i class="fa fa-cart-plus cart_size" aria-hidden="true"></i></span>&nbsp;Carrinho</a></li>
              <li><a href="../painel.php"><span class="glyphicon glyphicon-briefcase"></span> Painel</a></li>
                <li><a href="../../logout.php"><span class="glyphicon glyphicon-share-alt"></span> Logout</a></li>


                </li>
              </ul>
            </div><!-- /.navbar-collapse -->
            </div><!-- /.container-fluid -->
</nav>

    </header>
<body style="padding-top:60px;">

      <div class="container">
        <div class="row">
          <form>
          <table class="table table-striped table-hover" id="myTable">
            <thead>
            <h4></h4>
              <tr>
              <th>Image</th>
              <th>Produto</th>
              <th>Fabric</th>
              <th>Tamanho</th>
              <th>Qntd</th>
              <th>Valor</th>
              <th>sub.total</th>
              </tr>
            </thead>
            <tbody>



          <?php cart(); ?>


            </tbody>
          </table>
          </form>
              <div class="col-sm-4 pull-right">
              <h2>Total do pedido</h2>
              <table class="table table-bordered">
                <tr class="">
                  <th>Itens:</th>
                   <th class="text-center"><span>4</span></th>
                </tr>
                <tr >
                  <th>Valor total:</th>
                   <th class="text-center"><span>R$ 100,00</span></th>
                </tr>



              </table>

              </div>
        </div>

      </div>





</body>
<script src="../../js/jquery.min.js" type="text/javascript"></script>

<script src="../../js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
       var multi = $('.output');

        $.each(multi,function () {

           $('.btn').on('click', function() {

              $('.wr').load('  .output'); 
            });
        });


    </script>



<script>  //this deletes the rows in checkout page
function deleteRow(r) {
    var i = r.parentNode.parentNode.rowIndex;
    document.getElementById("myTable").deleteRow(i);
}
</script>


<script >
  $(function() {
    if (localStorage.getItem('fabric')) {
        $("#fabric option").eq(localStorage.getItem('fabric')).prop('selected', true);
    }

    $("#fabric").on('change', function() {
        localStorage.setItem('fabric', $('option:selected', this).index());
    });
});

</script>
<script >
  $(function() {
    if (localStorage.getItem('size')) {
        $("#size option").eq(localStorage.getItem('size')).prop('selected', true);
    }

    $("#size").on('change', function() {
        localStorage.setItem('size', $('option:selected', this).index());
    });
});

</script>

<script type="text/javascript">
 $('.actions').click(function(e){
    e.preventDefault();
    var action = $(this).attr('data_action'); //identifica a ação do botão
    var id = $(this).attr('product_id'); //id do produto
    $.ajax({
        url: 'cart_functions.php',
        type : 'GET', 
        data: {action:action,prod_id:id}, 
        dataType: 'json',
        success: function(data){
            //Quando a ação for PLUS 
            if(data.hasOwnProperty('plus')){
                if(data.plus == 'success'){
                   alert('added'); //em caso de sucesso
                } else {
                    alert('error'); //em caso de erro
                }
            }
            //Quando a ação for REMOVE 
            if(data.hasOwnProperty('remove')){
                if(data.remove == 'success'){
                    //em caso de sucesso
                } else {
                    //em caso de erro
                }
            }
            //Quando a ação for DELETE 
            if(data.hasOwnProperty('delete')){
                if(data.delete == 'success'){
                    //em caso de sucesso
                } else {
                    //em caso de erro
                }
            }
        }
    });
});
</script>
</html>
14
  • I don't think you have actually shown all the relevant code or explained very clearly. But do you mean that in the "Qntd" column there should only be one value in each row (e.g. the first row should show 414 and the second row should show 117 in that column)? Or have I missed the point entirely? Commented Sep 27, 2016 at 23:12
  • yes correct @ADyson Commented Sep 27, 2016 at 23:35
  • 1
    in that case you need to post the code which generates the table. So far all we've got is some javascript which loads some (unspecified) content and an out-of-context snippet of PHP. Commented Sep 28, 2016 at 8:20
  • $product = '<td... Shouldn't there be an opening <tr> before the <td>? You have a closing one later on. Commented Sep 28, 2016 at 11:48
  • yes i didnt saw that, i have a </tr> on the end of my code. maybe i erased it by mistake...i fix it now Commented Sep 28, 2016 at 11:53

1 Answer 1

1

ok, based on the comments and chat, plus the extra code you've posted I think I have got something which should work for you. You're actually not that far away. This will make it so that when you press the + or - buttons, the quantity of the related item will increase/decrease by 1 appropriately, and it will send the details of the change back to the server via ajax.

There are a few changes to make:

1) Remove the following JavaScript entirely:

<script type="text/javascript">
   var multi = $('.output');
   $.each(multi,function () {
   $('.btn').on('click', function() {
   $('.wr').load('  .output'); 
     });
   });
</script>

2) Change the code which generates the Qntd cell in the table as follows:

<td class="wr product'.$id.'">'.$value.'</td>

3) Edit this bit of JavaScript as follows:

<script type="text/javascript">
$('.actions').click(function(e){
  e.preventDefault();
  var action = $(this).attr('data_action'); //identifica a ação do botão
  var id = $(this).attr('product_id'); //id do produto
  console.log("triggered action " + action + " for product " + id); //debugging
  $.ajax({
    url: 'cart_functions.php',
    type : 'GET',
    data: {action:action,prod_id:id},
    dataType: 'json',
    success: function(data)
    {
      console.log("ajax call returned the following: " + JSON.stringify(data)); //debugging
      if (data.result == "success") {
        if (action == "plus" || action == "remove")
        {
          console.log("identified product td for " + id + ": " + $(".product" + id).length); //debugging
          $(".product" + id).text(data.val); //update the UI with the new total
        }
        else {
          //here do whatever you need to for the add/delete cases, that wasn't part of the question :-)
        }
      }
      else {
        alert("error");
      }
    },
    error: function(jqXHR, textStatus, errorThrown) { //in case of server/network error
      console.log("An error occurred whilst attempting to contact the server: " + jqXHR.status + " " + textStatus + " " + errorThrown);
    }
  });
});
</script>

4) Edit cart_functions as follows:

<?php header('Content-Type: application/json');
session_start();

if (isset($_GET['action'])) {
  $action = $_GET['action'];
  $prod   = $_GET['prod_id'];
  $prodname = 'product_'.$prod;
  $result;

  switch ($action) {
    case 'add':
        $result = add_prod($prod, $prodname);
    break;
    case 'plus':
        $result = plus_prod($prod, $prodname);
    break;
    case 'remove':
        $result = remove_prod($prod, $prodname);
    break;
    case 'delete':
        $result = delete_prod($prod, $prodname);
    break;
    default:
        $result = ['result'=>'error'];
    break;
  }
}

echo json_encode($result);

function add_prod($prod, $prodname){
  //sua função para add
 $_SESSION[$prodname] = 1;
 return ['result'=>'success'];
}

function plus_prod($prod, $prodname){
  $_SESSION[$prodname]++;
  return ['result'=>'success', 'val'=>$_SESSION[$prodname]];
}

function remove_prod($prod, $prodname){
  //sua função para remove
  $_SESSION[$prodname]--;
  return ['result'=>'success', 'val'=>$_SESSION[$prodname]];
}

function delete_prod($prod, $prodname){
  //sua função para delete
  $_SESSION[$prodname] = null;
  return ['result'=>'success'];
}
?>

5) put

session_start();

at the start of the PHP in checkout.php

Apologies if there are any syntax errors in there, I didn't have time to test anything.

Sign up to request clarification or add additional context in comments.

11 Comments

i tested and it didnt work, i check the syntax errors but still didnt update my value
I've added some debugging to the javascript. Can you monitor your browser console (F12) while pressing the buttons and see what it reports, and check the results are as you would expect? If you're unsure, post the output here.
got some SyntaxErrors and i fix it and now i got this triggered action undefined for product 171 <--- first product in the picture
sorry change var action = $(this).data('action'); to var action = $(this).attr('data_action'); - hadn't noticed that your button uses _ between data and action therefore it won't be read as a "data" value accessible by .data(); (it would have to use - instead of _). I have updated the answer.
any change in the messages that get logged in the console?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.