I am trying to activate
or deactivate
the products for a form using $product->status
The active button shows if $product->status
is 0 and
The deactive button shows if $product->status
is 1
I want to toggle the value of $product->status
in the mysql database every time I click on the button
<form action="{{route('invetory.create')}}" method="POST">
@csrf
<table id="dynamicTable">
<tr>
<th>item</th>
<th>tax</th>
<th>Action</th>
</tr>
@forelse($products as $product)
<input type="text" name="item" value="{{$product->id}}
hidden />
<td>
<input type="text" name="item" value="{{$product->item}}
/>
</td>
<td>
<input type="text" name="tax" value="{{$product->tax}}
/>
</td>
@if($product->status =='0')
<td>
<button type="button" >active</button>
</td>
@else
<td>
<button type="button" >Deactive</button>
</td>
@endif
</table>
</form>
CodePudding user response:
You could add some data attributes to your buttons, and use them in js to send an ajax request
@if ($product->status =='0')
<td>
<button type="button" data-product="{{ $product->id }}" data-status="{{ $product->status }}">active</button>
</td>
@else
<td>
<button type="button" data-product="{{ $product->id }}" data-status="{{ $product->status }}">Deactive</button>
</td>
@endif
document.querySelectorAll('.toggle-tr').forEach(el => el.addEventListener('click', e => {
const product = e.target.dataset.product;
const status = e.target.dataset.status == 0 ? 1 : 0;
// send ajax or fetch request passing in product_id. If we're going with a RESTful approach,
axiox.patch(`/products/${product}`, { status })
.then(res => { ... })
.catch(err => { ...});
}));
CodePudding user response:
You can use jQuery ajax here:
Pass product id in data-id
attribute
@if($product->status =='0')
<td>
<button type="button" data-id="{{ $product->id }}" >active</button>
</td>
@else
<td>
<button type="button" data-id="{{ $product->id }}" >Deactive</button>
</td>
@endif
then use ajax:
$(document).on('click', '.active_btn', function(e) {
e.preventDefault();
let id = $(this).data('id');
$.ajax({
url: '{{ route("products.update") }}',
method: 'PUT',
data: {
id: id,
status: 1,
_token: '{{ csrf_token() }}'
},
success: function(response) {
console.log(response);
}
});
});
$(document).on('click', '.deactive_btn', function(e) {
e.preventDefault();
let id = $(this).data('id');
$.ajax({
url: '{{ route("products.update") }}',
method: 'PUT',
data: {
id: id,
status: 0,
_token: '{{ csrf_token() }}'
},
success: function(response) {
console.log(response);
}
});
});
Now you can handle the request in the controller.