John Davidson

javascript - Foreach Condition with Ajax form submit button

0 comments
Message:


I was trying to do for each condition for form but for some reason, it is submitting all foreach data with ajax.


@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


_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



My Answer:
To fix this issue, you need to target the specific form that is being submitted instead of all forms on the page. You can do this by using $(this) to reference the form that triggered the submit event. Here's an updated version of your code:

javascript
@foreach($response['Types'] as $type)


${{ number_format($type['price']['subTotal'],2)}}


Per Day Parking





@CSRF








@endforeach




In this updated code, I changed the button id to a class "chkbtn" and used $(this) to reference the form that contains the clicked button. This way, only the data from the specific form that is being submitted will be sent to the cart.

Rate this post

5 of 5 based on 4634 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us