I was trying to do for each condition for form but for some reason, it is submitting all foreach data with ajax.
JavaScript
x
@foreach($response['Types'] as type)
<div class="option option-two">
<div class="upper">
<p style="font-size: 2em;font-weight: bold">${{ number_format($type['price']['subTotal'],2)}}</p>
<p style="font-weight: bold">Per Day Parking</p>
</div>
<div class="form">
<form name="{{$type['id']}}" method="post" class="reds">
@CSRF
{{--<input type=hidden name=LotId value="{{ json_encode($response, true) }}">--}}
<input type=hidden name=subtotal value="{{ number_format($type['price']['subTotal'],2) }}">
<input type=hidden name=fees value="{{ number_format($type['price']['taxesAndFeesAmount'],2) }}">
<input type=hidden name=total value="{{ number_format($type['price']['total'],2) }}">
<button id="chkbtn" style="box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.2), 0 2px 10px 0 rgba(0, 0, 0, 0.1);">Add to Cart</button>
</form>
<script>
$(function () {
$("form[name='{{$type['id']}}']").submit(function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: '/options1',
data: $('form').serialize(),
success: function (result) {
$("#iDiv").html(result);
}
});
});
});
</script>
@endforeach
For some reason the response is
JavaScript
_token: Ve4UHceRA6OVYTdTzGdFvXxHkA14v74oy4Y4pCVz
subtotal: 23.90
fees: 4.99
total: 28.89
_token: Ve4UHceRA6OVYTdTzGdFvXxHkA14v74oy4Y4pCVz
subtotal: 23.90
fees: 4.99
total: 28.89
_token: Ve4UHceRA6OVYTdTzGdFvXxHkA14v74oy4Y4pCVz
subtotal: 27.90
fees: 4.99
total: 32.89
i want to send only one option data to the cart. But, its adding all foreach data to cart
Please help, Thanks
Advertisement
Answer
JavaScript
data: $('form').serialize()
This will serialize all forms mounted on the webpage. Instead you should serialize the submitted form only, just as you did for the submit event handler.
JavaScript
data: $("form[name='{{$type['id']}}']").serialize()
or shorthand
JavaScript
data: $(this).serialize()
will serialize only particular form instead of all forms.