I am trying to build a system where the product-container will display a form or a button depending on if the product is currently in the cart or not. I have an Ajax post system that seems to work fine, but I shall include that too. I have a front Controller which sends the Cart Content and the Products.
The problem is that when I refresh the page my form is supposed to replace the buy button for the given product, but it does not work. Only the Ajax post to Cart system works.
My view (which includes some of the javascript/php):
<?php $countP = 0; ?>
@foreach($products as $product)
<input type="hidden" id="product_id<?php echo $countP; ?>" value="
{{$product->id}}">
<div class="item main-product-container">
<a href="#"<i class="fa fa-exclamation" aria-hidden="true"></i>
</a>
<div class="product-img text-center">
<img src="{{url('img', $product->image)}}">
</div>
<p class="price text-center">{{$product->price}},- kr</p>
<div class="product-title">{{$product->name}}</div>
<script>
<?php foreach($cartContents as $cartContent) { ?>
if(<?php echo $cartContent->id ?> = {{$product->id}})
{
$('.cartBtn{{$product->id}}').hide();
$('.productForm{{$product->id}}').show();
} else {
$('.cartBtn<?php echo $product->id;?>').show();
$('.productForm<?php echo $product->id;?>').hide();
}
<?php } ?>
</script>
<form class="productForm{{$product->id}} productForm"
id="productForm<?php echo $countP;?>">
<input class="qty-input" name="qty" id="qty" type="integer"
value="1">
<input type="hidden" id="id" name="id" value="{{$product->id}}">
<input type="submit" id="ajaxSubmit{{$product->id}}"
class="cart-button" value="Legg til">
</form>
<button class="btn btn-default add-to-cart cartBtn<?php echo
$product->id;?>" id="cartBtn<?php echo $countP;?>">Kjøp</button>
</div>
<?php $countP++?>
@endforeach
</div>
My Ajax:
<script>
$(document).ready(function() {
$('.productForm').hide();
<?php $maxP = count($products);
for($i=0;$i<$maxP; $i++){
?>
$('#cartBtn<?php echo $i;?>').click(function() {
var product_id<?php echo $i;?> = $('#product_id<?php echo $i;?
>').val();
$.ajax({
type: 'get',
url: '<?php echo url('/cart/post');?>/'+ product_id<?php echo $i;?>,
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
},
success:function() {
$('#cartBtn<?php echo $i;?>').hide();
$('#productForm<?php echo $i;?>').show();
},
});
});
<?php } ?>
});