Reputation: 405
i am using laravel, i have a list of letters, i want to when i clicked on row, background color of that row changes.
im doing this with ajax.
this is my ajax: Ajax
this is my letter_table : letter table
i have read_letter
with two numbers 0,1
with default value 0
, when value is 0
letter is unread and when value is 1
letter is read.
this is my view for letter list : Letter list view
and this is view of letter list in browser when i dont open any letter : letter list
and this is view of letter when i open letter : letter list
but my problem is when i clicked on other letters, it doesnt work, just on first item of the list working well.
this is my controller : update read_letter in database
Edit : here is codes
ajax :
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#update_ajax").on('click', function () {
var letter_id = $(this).data('id');
var read_letter = 1;
$.ajax({
type: "GET",
dataType: "json",
url: "/Letter/changeRead",
data: {'letter_id': letter_id, 'read_letter': read_letter},
success: function (data) {
console.log(data.success);
}
});
});
});
update letter_read in letterController :
public function updateLetterRead(Request $request)
{
$letter = Letter::find($request->letter_id);
$letter->read_letter = $request->read_letter;
$letter->save();
return response()->json(['success' => 'نامه خانده شد']);
}
button for show letter :
<td>
<a href="{{ route('Letter.show',$letter->id) }}"
data-id="{{ $letter->id }}"
id="update_ajax">
<i class="fas fa-eye"></i>
</a>
</td>
Upvotes: 1
Views: 839
Reputation: 1943
Its happening because you are triggering for id and its coming multiple times in view. So convert it as class.
"Id's are used to describe a HTML element uniquely". DOC
So in jQuery update $("#update_ajax")
to $(".update_ajax")
and in view remove id="update_ajax"
and add class="update_ajax"
Another Hack method is :
update $("#update_ajax").on('click', function()
To $('tbody').on("click","#update_ajax",function()
But above suggestion is the right and need to be the selected one.
Upvotes: 1
Reputation: 619
The #update_ajax
id is repeating for every row of the table. HTML ids should be unique.
Change the id to a class:
<td>
<a href="{{ route('Letter.show',$letter->id) }}"
data-id="{{ $letter->id }}"
class="update_ajax">
<i class="fas fa-eye"></i>
</a>
</td>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".update_ajax").on('click', function () {
var letter_id = $(this).data('id');
var read_letter = 1;
$.ajax({
type: "GET",
dataType: "json",
url: "/Letter/changeRead",
data: {'letter_id': letter_id, 'read_letter': read_letter},
success: function (data) {
console.log(data.success);
}
});
});
Upvotes: 1