I am looping through data form a database to a form that makes a Ajax request to add an item to a shopping basket/cart. Everything works fine except that only the first item in the array is added? I have tried using classes as apposed to id's(unique
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>";
) My JS code is as follows:
$('#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()
}
});
</div>
You can not have the same one ID for a different inputs. ID must be UNIQUE. Instead of ID use CLASS attribute
1- Sometimes because of caching problem it will not work so you have to add seed to your call.
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
s only for one element. They must be unique. You can use CLASS
instead.</div>