i want to use foreach id to send via ajax request.
@foreach ($AssetsGroup as $AssetGroup)
<tr>
...
<td>
<button id="btn_add{{ $AssetGroup->id }}" data-asset-group-id="{{ $AssetGroup->id }}">افزودن دارایی</button>
</td>
....
</tr>
@endforeach
ajax request
$(document).on('click','#btn-save',function(){
var formDatas = {
name: $('#name2').val(),
group: // from foreach id,
tags: $('#tags2').val(),
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
type: 'post',
url: 'asset' ,
data: formDatas,
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
……………………………………………………………………………….
2
Answers
Ids should be unique for each element. You should use classes instead. Replace the id attribute with a class like the following :
<td class="btn_add">
Also see that in your script you put the event listener on a different id (id in html = btn_add, in js is btn-save)
This way, each button with the class btn_add will fire the event below and you can get the group id by using
$(this).data('asset-group-id')
like soYour question is a bit vague but I think this’ll help.