Each row of my DataTable is a product, and in each row there is form which adds product to basket when submitted. I thought it would be more elegant if I do that without page refresh. I've added a function to fnDrawCallback, but it is being executed multiple times - as many times as this table row is being redrawn (filtering, coming back to the same table page).
Php:
<td class="add-to-basket-form" id="<?php echo str_replace('/', '', $productPartCode); ?>">
<p class="product-description-mobile visible-xs"><?php echo $productDescription; ?></p>
<p class="product-partcode-mobile visible-xs"><?php echo $productPartCode; ?></p>
<p class="product-price-mobile visible-xs">£<?php echo $showPrice; ?></p>
<form method="post" class="add-to-basket-submit" action="extras.php?site=<?php echo $_SESSION['basketSiteNo']; ?>&action=add&code=<?php echo $productPartCode; ?>">
<input class="add-to-basket-qty" type="text" name="quantity" value="1" size="2"/>
<input class="add-to-basket-description" type="text" name="description" value="<?php echo $productDescription; ?>" style="display:none;" />
<input class="add-to-basket-price" type="number" name="price" value="<?php echo $showPrice; ?>" style="display:none;" />
<input class="add-to-basket-img" type="text" name="img" value="<?php echo $productImage; ?>" style="display:none;" />
<input class="add-to-basket-thumb" type="text" name="thumb" value="<?php echo $productThumb; ?>" style="display:none;" />
<button class="add-to-basket-button" type="submit"><span class="glyphicon text-tw-red glyphicon-plus-sign"></span></button>
</form>
</td>
JavaScript:
$('#myDataTable').dataTable({
"fnDrawCallback": function() {
$(".add-to-basket-submit").on('submit', function() {
var item = $(this).parent().attr('id');
var action = $(this).attr('action');
var quantity = parseInt($(this).children('.add-to-basket-qty').val());
var description = $(this).children('.add-to-basket-description').val();
var price = Number($(this).children('.add-to-basket-price').val());
var img = $(this).children('.add-to-basket-img').val();
var thumb = $(this).children('.add-to-basket-thumb').val();
$.post(action, { quantity: quantity, description: description, price: price, img: img, thumb: thumb } );
var numberOfItemsInBasket = parseInt($('.number-of-items-in-basket').html());
var totalOfBasket = Number($('#total-of-basket').html());
numberOfItemsInBasket = numberOfItemsInBasket + 1;
$('.number-of-items-in-basket').html(numberOfItemsInBasket);
totalOfBasket = totalOfBasket + (quantity*price);
totalOfBasket = totalOfBasket.toFixed(2);
$('#total-of-basket').html(totalOfBasket);
$('#' + item).find('form').hide();
$('#' + item).append('<div class="in-basket-info">in basket</div>');
return false;
});
}
});
Similar problem was described here.
In my case using .on did not help. I've also tried to place the function in initComplete, but this only works when tables is drawn first time, and not after table is redrawn.
Please help.