Reputation: 1983
I want to be able to update the database when I click on a li item but I am having a hard time to find an answer to this question. I know there are hundreds of similar questions but I haven't been able to get an answer specific to my question, for use with laravel.
This is my route for updating the database:
Route::post('api/tasks/update/{id}', function($id) {
$task = App\Task::find($id);
$task->completed = Request::get('completed');
$task->save();
});
I just have an unordered list with some li's on my view, and once clicked on one of those views, I want to set a specific value in the database to either 0
or 1
.
Here is my database table for tasks:
CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`completed` tinyint(1) NOT NULL DEFAULT '0'
)
As you can see it is a simple id
field, name
field and completed
field. My view:
<ul>
@foreach($tasks as $task)
<li>{!! $task->name !!}</li>
@endforeach
</ul>
So I basically only need a pointer in the right direction for the actual AJAX call.
Upvotes: 0
Views: 2614
Reputation: 3520
I would recommend you use a GET
request, to make a call ajax, first bind the id to the li
element
@foreach($tasks as $task)
<li data-id='{!! $task->id !!}'>{!! $task->name !!}</li>
@endforeach
and use this jQuery function:
$(document).ready(function(){
$('li').on('click', function(e){
$.ajax({
url: 'api/tasks/update/'+$(this).data('id'),
method: 'GET'
}).then(function(){
alert('success');
});
});
})
and finally, change your route from post to get.
Route::get(...
Upvotes: 1