The page I currently have shows a table that dynamically generates rows showing user information. Each row has an Edit button that, when clicked, turns the respective cells into inputs, and turns the Edit button into a Save button. When that button's clicked, the input values for that user's row should be stored into the database.
I admittedly don't have a lot of experience with Ajax, but I've been looking online and I do believe I'm following the general procedure for calling a Controller function through an Ajax call properly. However, I'm still getting a 500 error when I try to test it. I believe it may be in how I am obtaining the request and sending back the response, but I'm unsure of the specific error.
My code contains as follows:
home.blade.php
....
@foreach($users as $user)
<tr id="row{{ loop->iteration }}>
<input type='text' id='first_name_input_row{{ loop->iteration }}'>
<input type='text' id='last_name_input_row{{ loop->iteration }}'>
<input type="button" id="save_button_row{{ $loop->iteration }}" class="btn btn-btn-submit" value="Save" class="save" onclick="save_row('{{ $loop->iteration }}', {{ $user }})">
</tr>
@endforeach
....
<script>
function save_row(num, user)
{
var id = 'row' + num;
$.ajax({
method: 'post',
url: '/update-table',
data: {
'_token': $('input[name=_token]').val(),
'first_name': $('input[id=first_name_input_' + id + ']').val(),
'last_name': $('input[id=last_name_input_' + id + ']').val(),
'user': user
},
success: function(response){
console.log("It worked!");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("It failed!");
console.log(jqXHR);
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
</script>
HomeController.php
public function updateTable(Users $users){
$user = request()->input('employee');
$first_name = request()->input('first_name');
$last_name = request()->input('last_name');
$users->editUser($user, $first_name, $last_name);
return response()->json($user);
}
Users.php
public function editUser($user, $first_name, $last_name) {
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->save();
}