James Allan James Allan - 1 month ago 5
Ajax Question

Dropdown in loop only gets the first item value from foreach loop php/ajax

I got two dropdowns for my product in my cart.
All products are stored in sessions inside of a foreach loop.
But my dropdowns only work for the first product from loop.
Exemple: if i have 2 products in my cart the fisrt product row gets the cost based on both dorpdowns.
but the second product is getting the same cost from the first dropdown.
can someone please tell me how to fix this.

my script in checkout.php

$(document).ready(function() {

$('.fabric, .size').on('change', sendData);

function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
var cost = $(this).attr('data-id');
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:cost,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + cost).text(data.val);

});
}
}
});


My php foreach loop in cart.php

function cart(){
global $conn;


$fabric_options = '<option>Select Fabric</option>';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){

$tecido=$rows['tecido'];
$id_price=$rows['id_price'];
$t50='50';
$t45='45';

$fabric_options .= '<option value="'.$id_price.'">'.$tecido.'</option>';
}

if(!isset($_SESSION['icms'])) {
$_SESSION['icms']='0';
}else{
$_SESSION['icms'];
}

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);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];

$btn_add ='<button type="button" 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></button>';

$btn_remove ='<button type="button" 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></button>';

$btn_delete ='<button type="button" 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></button>';

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

$product = '
<tr>
<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 name="fabric" class="fabric select form-control selectpicker" required="" data-id="'.$id.'">
'. $fabric_options . '
</select>
</td>

<td>
<select data-id="'.$id.'" class="select size form-control selectpicker" required style="width:80%;" >
<option>Select size</option>
<option value="'.$t50.'">50x'.$t50.'</option>
<option value="'.$t45.'">45x'.$t45.'</option>

</select>
</td>
<td class="product'.$id.'">'.$value.'</td>
<td class="icms">R$: '.$_SESSION['icms'].'</td>
<td class="total'.$id.'" data-id="'.$id.'">R$: '.$value * $_SESSION['icms'] .' </td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;

}
}
}
}
}


and this is where my calculations are made..

calculates.php

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

include_once '../incluedes/conn_cms.php'; //session allways start here

if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$prod = $_GET['prod_id'];
$prodname = 'product_'.$prod;

$query3 =" SELECT * FROM valores_almofadas WHERE size='$size_id' AND price_id ='$fabric_id'";

$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){

if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;

}
echo json_encode( $_SESSION['icms']);
}


how can i make my dropdown work foreach product?

Answer

The problem is that var fabricID = $(".fabric").val() is selecting the value from the first element it finds with the fabric class. This will be the same element (the first one) every time, no matter how many elements exist on the page with that class.

You need to select the value from the correct elements. This is made slightly trickier by the fact that you need to send both the fabric and size values simultaneously. Luckily you have got the row ID as a data attribute on both the <select> elements, so we can use this to match them up.

$(document).ready(function() {

  $('.fabric, .size').on('change', sendData);

  function sendData() {
   //use the data-id attribute of the selected element to match the correct elements
   var id = $(this).data("id");
    var fabricID = $('.fabric[data-id=' + id + ']').val(); 
    var sizeID   = $('.size[data-id=' + id + ']').val();

    if ( fabricID !== "" && sizeID !== "") {
      $.ajax({
            type     : 'GET',
            url      : 'calculates.php',
            dataType : 'json',
            data     : {
                prod_id:id,
                fabric_id: fabricID,
                size_id: sizeID
            }
        }).done(function(data) {
            $('.icms' + id).text(data.val);

        });
      }
  }
});
Comments