0

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.

3
  • 1
    Are you just looking for the jQuery $.post() function? Commented Apr 22, 2016 at 13:45
  • Yeah I have no idea what the ajax call should look like since I am not into javascript at all Commented Apr 22, 2016 at 13:47
  • Assign the unique id to each <li> and using "on" function of jQuery as you content will generate dynamically Commented Apr 22, 2016 at 14:01

1 Answer 1

1

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(...
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is what I needed, from this I can get it to work, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.