Search code examples
phpajaxlaravellaravel-9

How to show new added record on table with Ajax (no refreshing)


I'm working with Laravel 9 to develop a todo list with Ajax applied.

So basically I tried to create new task with post ajax request:

$('#AddButton').click(function(event){
        var text = $('#addItem').val();
        $.post('tasks-list-add', {'text': text, '_token': $('input[name=_token]').val()}, function(data){
          
         });
});

But now the problem is, it does not work out at all and not refreshes the page after the submission in order to show the new added record on the table.

So how can I fix this issue? And it will create a new record of task by running create method of this Controller Class:

class TaskListController extends Controller
{
    public function index()
    {
        $tasks = Tasklist::all();
        return view('admin.tasks.list',compact('tasks'));
    }
    
    public function create(request $request)
    {
        $item = new Tasklist();
        $item->task_name = $request->text;
        $item->save();
        
        return 'Done';
    }
}

But I wanted the new task to be shown in the page without refreshing.

So I tried adding id of items:

                <div id="items">
                    @php($menuCounter = 1)
                    @forelse($tasks as $task)
                        <tr>
                            <td>{{ ++$menuCounter }}</td>
                            <td class="ourItem" data-toggle="modal" data-target="#exampleModalCenter">{{ $task->task_name }}</td>
                        </tr>
                        @empty
                            <td colspan="5" class="text-center">Nothing here to show</td>
                    @endforelse
                </div>

And then:

$.post('tasks-list-add', {'text': text, '_token': $('input[name=_token]').val()}, function(data){
        $('#items').load(location.href + ' #items');    
});
            

Solution

  • once you get the response from your ajax

    you can update the content of a html table as following

    $('#AddButton').click(function(event){
            var text = $('#addItem').val();
            $.post('tasks-list-add', {'text': text, '_token': $('input[name=_token]').val()}, function(data){
              if(data=="Done") {
                 $('#items').append(
                  '<tr>'+
                    '<td>new_id</td>'+
                    '<td class="ourItem" data-toggle="modal" data-target="#exampleModalCenter">'+text+'</td>'
                  '</tr>'
                 );
              }
             });
    });