After i click the remove image if the array have 7 item one remove and i click another it remove another one item but array still 6 it didn't update the last one i delete how can i solve it thanks you for ur time
Jquery
$(document).on('click', '.remove-image', function() {
var id = $(this).attr('id');
var product_id =$(this).attr('product_id');
var name =$(this).attr('name');
var array=$(this).attr('array');
var arr = JSON.parse(array);
// confirm("Are You sure want to delete !");
var arr = arr.filter(val => val !== name);
console.log(arr);
var formData = {
id: id,
product_id : product_id,
image: arr
};
// $.ajax({
// type: "POST",
// url: "{{ url('image/delete') }}",
// data: formData,
// success: function () {
// alert('workinggggg');
// },
// error: function () {
// alert('errorrrrrrrr');
// }
// });
$(this).parent('div').remove();
});
Laravel Blade
@foreach (json_decode($gallery->image) as $key => $image)
<div>
<span name="{{ $image }}" id="{{ $gallery->id }}" product_id="{{ $product->id }}" array="{{ $gallery->image }}"
class="flex text-red-400 pl-3 image cursor-pointer remove-image">X</span>
<img src="{{ asset('storage/' . $image) }}" class="pr-5" alt="{{$product->slug}}">
</div>
{{ var_export($key) }}
@endforeach
Your code is correctly gets a filtered array, but it doesn't write the result back to the attribute, and so the next time that code executes, the array is built again from the attribute's value, which still has the original JSON.
So add one statement to this part:
var array = $(this).attr('array');
var arr = JSON.parse(array);
var arr = arr.filter(val => val !== name);
$(this).attr('array', JSON.stringify(arr)); // <---