I am trying to delete a row from a table using jquery ajax. After couple of trying I cant figure out why my code (deleting part) is not working as I am new with ajax and javascript. Loading data with ajax from server works fine and the script has no console error. When I press delete, I see nothing on network tab. Here is my code:
routes.php
Route::delete('users/{id}','AjaxController@destroy');
AjaxController.php
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
}
view:
<table id="users" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody id="abc">
</tbody>
</table>
script:
$(document).ready(function(){
var $tbody = $('#abc');
// getting data from server
$.ajax({
type : 'GET',
url : 'api/users',
success: function(users) {
$.each(users, function(i, user){
$tbody.append('<tr id="user_' + user.id + '"><td>'+user.name+'</td><td>'+user.phone+'</td><td><button type="button" class="btn btn-xs btn-danger" id="delete" value="'+user.id+'" name="button">Delete</button></td></tr>');
});
},
error: function(){
alert('error loading data');
}
});
// deleting data
$('#delete').on('click', function(e){
var user_id = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
var user = {
id : user_id
};
$.ajax({
type: 'DELETE',
url : '/user/'+user.id,
success : function(deleteUser)
{
$("#user_" + user_id).remove();
},
error : function()
{
alert('error deleting data');
}
});
}); // deleting block ends
});
});
$idin yourdestroyfunction. Try printing it._methodfield in your ajax requests.