2016-09-28 66 views
0

我正在通過數據庫中的數據循環到一個表單,該表單會向Ajax請求添加項目到購物籃/購物車。一切正常,只有數組中的第一項被添加?使用類作爲並列爲ID的(唯一PHP:試圖從foreach循環中調用ajax調用

echo "<div class='col-100 border-temp bg-orange'>"; 
 
echo "<div class='col-50 border-temp'>"; 
 

 
foreach ($result as $key => $result) { 
 
    $m = $result["model_no"]; 
 
    $q = $result["qty_available"]; 
 
    
 
    echo "<form method='post' action='/stock-clearance' class='stock_clearance bg-blue'>"; 
 
    echo "<label for='model_no'><h2>Model No</h2></label>"; 
 
    echo "<input id='model_no' name='model' type='text' placeholder='Paste model no... ' value='$m' />"; 
 
    echo "<span id='model_error'></span>"; 
 
    echo "<label for='quantity'>Quantity</label><br />"; 
 
    echo "<input id='quantity' name='quantity' value='1' type='number' min='1' max='$q'>"; 
 
    echo " <span id='quantity_error'></span>"; 
 
    //echo "<input id='sc_add_to_cart' name='' value='$key' type='button'>"; 
 
    echo "<input id='sc_add_to_cart' name='sc_add_to_cart' value='Add to Basket' type='submit'>"; 
 
    echo "</form>"; 
 
} // End foreach loop 
 
echo "</div>";

)我已經試過 我的JS代碼如下:

$('#sc_add_to_cart').on('click', function(e) { 
 

 
     e.preventDefault(); 
 
     var form = $('.stock_clearance'); 
 
     hideStockClearanceMessages(form); 
 

 
     var request = $.ajax({ 
 
      beforeSend: function() { form.css({ opacity: 0.4 }); }, 
 
      url: 'ajax.php', 
 
      cache: 'false', 
 
      data: { 
 
       action: "sc-add-to-cart", 
 
       model: $('input[name="model"]').val(), 
 
       quantity: $('input[name="quantity"]').val() 
 
      } 
 
     });

enter image description here

回答

0

對於不同的輸入,您不能具有相同的一個ID。 ID必須是唯一的。代替ID使用CLASS屬性

0

1-有時由於緩存問題,它不會工作,因此您必須將種子添加到您的呼叫。

function seed() { 
 
    return Math.floor((Math.random() * 10000) + 1); 
 
} 
 

 
$('#sc_add_to_cart').on('click', function(e) { 
 

 
     e.preventDefault(); 
 
     var form = $('.stock_clearance'); 
 
     hideStockClearanceMessages(form); 
 

 
     var request = $.ajax({ 
 
      beforeSend: function() { form.css({ opacity: 0.4 }); }, 
 
      url: 'ajax.php?sid=' + seed(), 
 
      cache: 'false', 
 
      data: { 
 
       action: "sc-add-to-cart", 
 
       model: $('input[name="model"]').val(), 
 
       quantity: $('input[name="quantity"]').val() 
 
      } 
 
     });

  • 請使用ID唯一一個元件。它們必須是唯一的。您可以改用CLASS
  • +0

    試過但沒有工作;( – Gary