Jquery在循环内更新div并显示所有值

时间:2016-09-27 22:37:02

标签: javascript php jquery ajax

我的购物车中有一个foreach循环。 因此,当我点击我的加号或删除按钮时,我的$value更新正常。 但我在每一行都获得双倍价值。

这是我的剧本。

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

看一下这张照片,了解最新情况...... 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>

1 个答案:

答案 0 :(得分: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();

在checkout.php中的PHP开头

如果有任何语法错误,我很抱歉,我没有时间测试任何东西。