2016-09-27 152 views
1

我在我的购物车中获得了一个foreach循环。 所以当我点击我的加号或删除按钮时,我的$value更新正常。 但即时通讯每行获得双倍的价值。Jquery更新循环内的div并显示所有值

这是我的脚本。

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


    </script> 

和我的PHP foreach循环内我有这个。

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

我想要的只是当我点击我的btn类时只更新那个div。

我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>'; 

看看这款PIC明白怎么回事... enter image description here

我怎样才能解决这个问题?

我cart.php哪里是我的foreach循环...

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; 
      } 
      } 
     } 
     } 
    } 

这个处理我的按钮功能。 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']); 
} 

?> 

所有这一切都在我的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> 
+0

我不认为你实际上已经显示了所有相关的代码或非常清楚地解释。但是,你的意思是说,在“Qntd”列中,每行只能有一个值(例如,第一行应该显示414,第二行应该显示该列中的117)?或者我完全错过了这一点? – ADyson

+0

是的正确@ADYSON –

+1

在这种情况下,你需要发布生成表的代码。到目前为止,我们所得到的只是一些JavaScript,它会加载一些(未指定的)内容和PHP的一段不合适的片段。 – ADyson

回答

1

确定的基础上,评论和聊天,再加上你已经发布了额外的代码我被渲染认为我有一些应该为你工作的东西。你其实并不遥远。这将使得当您按下+或 - 按钮时,相关项目的数量会适当增加/减少1,并且会通过ajax将更改的详细信息发送回服务器。

有一些变化,使:

1)删除以下JavaScript完全:

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

2)改变,其产生在表中Qntd小区中的代码如下:

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

3)编辑的JavaScript的该位如下:

<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)编辑cart_functions如下:

<?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)把

session_start(); 

在PHP开始在checkout.php

道歉,如果有任何语法错误在那里,我没有时间去测试任何东西。

+0

我测试过,它没有工作,我检查语法错误,但仍然没有更新我的值 –

+0

我已经添加了一些调试的JavaScript。你可以在按下按钮的同时监视浏览器控制台(F12)并查看它报告的内容,并检查结果是否如你所期望的那样?如果您不确定,请在此输出。 – ADyson

+0

得到了一些语法错误,我修好了,现在我得到了这个'触发的操作未定义的产品171' <---图片中的第一个产品 –