Ron Brouwers Ron Brouwers - 7 months ago 12
Javascript Question

TODO List updating with ajax

So I have this simple todo list with an ajax call to update the field

completed
in my database to either 1 or 0, when I click on a li item.

The code in my view is not good, obviously, and it ofcourse doesn't work. Only the first time, when I click on a li, it does get updated, but I need to refresh if I want it to work again, since the
data-completed
doesn't get updated. I need jquery to do that, but I have no clue how to update a data-attribute to either 1 or 0 based on the original value.

Any pointers as to how to make this work properly will be greatly appreciated.

View:

<li data-id='{!! $task->id !!}' data-completed='@if($task->completed == '1') 0 @else 1 @endif'>


AJAX Call:

$('li').on('click', function(e){
$.ajax({
url: 'api/tasks/update/'+$(this).data('id')+'/'+$(this).data('completed'),
method: 'GET'
})
});


Since I am using laravel, this is my route:

Route::get('api/tasks/update/{id}/{completed}', function($id, $completed) {
$task = App\Task::find($id);

$task->completed = $completed;

$task->save();
});

Answer

There's a few things you need to do here:

First, you don't need your if statement if you're already saving 0/1 in the database, so you can simplify your view portion:

<li data-id='{!! $task->id !!}' data-completed='{{ $task->completed }}'>

Second, you'll need to return the updated task so that you can update your view:

Route::get('api/tasks/update/{id}/{completed}', function($id, $completed) {
    $task = App\Task::find($id);

    $task->completed = $completed;

    $task->save();

    return response()->json($task);
});

Then, update your ajax call so that when the updated task is returned, you can update your list:

$('li').on('click', function(e){
    var completed = (!$(this).data('completed') ? 1 : 0);
    $.ajax({
        url: 'api/tasks/update/'+$(this).data('id')+'/'+$(this).data('completed'),
        method: 'GET',
        success: function(data) {
          $(this).data('completed', data.completed);
       },
    })
});

Something I would also do is update your route and AJAX calls to POST, as this is just good practice for when you're updating data:

PHP

Route::post('api/tasks/update/{id}', function(Request $request, $id) {
    $task = App\Task::find($id);

    $completed = $request->input('completed');

    $task->completed = $completed;

    $task->save();

    return response()->json($task);
});

JS

$('li').on('click', function(e){
    $.ajax({
        url: 'api/tasks/update/'+$(this).data('id'),
        data: {completed: (!$(this).data('completed') ? 1 : 0)},
        method: 'POST',
        success: function(data) {
          $(this).data('completed', data.completed);
       },
    })
});
Comments