Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Danny971's avatar

trying to reload section of web application without reloading whole page

Im trying to reload my todo list with new task everytime a task is added

here is my code this far


Javascript

$(document).ready(function() {
    // Add CSRF token to all AJAX requests
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });



    // Handle Enter key press on the input field
    $('.tdl-new').keypress(function(event) {
        if (event.which === 13) { // Check if the key pressed is Enter (key code 13)
            event.preventDefault(); // Prevent the default behavior of the Enter key (form submission)

            // Get the task from the input field
            var task = $(this).val().trim();

            if (task !== '') {

               
                // Make an Ajax request to save the task
                $.ajax({
                    url: $('#todo_list').data('save-todo'), // Use the data attribute
                    method: 'POST',
                    data: { todo: task },
                    success: function(response) {
                        // Clear the input field
                        $('.tdl-new').val('');

                        // Update the todo list based on the response
                     $('#todo_list ul').append(response);
                      
                     $(document).trigger('todolistUpdated');
                        
                    }, 
                    error: function(error) {
                        // Handle the error
                    }
                });

           
            

            } 
        }
    });

    // Handle checkbox change event
    $('input[type="checkbox"]').change(function() {
        var taskId = $(this).data('task-id');
        var status = $(this).is(':checked') ? 1 : 0;

        // Make an Ajax request to update the task status
        $.ajax({
            url: $('#todo_list').data('update-todo-status').replace(':id', taskId), // Use the data attribute
            method: 'POST',
            data: { status: status },
            success: function(response) {
                // Handle the success if needed
            },
            error: function(error) {
                // Handle the error
            }
        });
    });
});


Html

here is the html

                   <div class="col-xl-4 col-xxl-6 col-lg-6 col-md-12 col-sm-12">
    <div class="card">
        <div class="card-header">
            <h4 class="card-title">Todo</h4>
        </div>
        <div class="card-body px-0">
            <div class="todo-list">
                <div class="tdl-holder">
                    <div class="tdl-content widget-todo2 mr-4">
                        <ul id="todo_list" 
                            data-save-todo="{{ route('save-todo') }}" 
                            data-update-todo-status="{{ route('update-todo-status', ':id') }}">
                            @foreach ($tasks ?? [] as $task)
                                <li>
                                    <label>
                                        <input type="checkbox" data-task-id="{{ $task->id }}" {{ $task->task_status ? 'checked' : '' }}>
                                        <i></i><span>{{ $task->task_name }}</span> <a href='#' class="ti-trash"></a>
                                    </label>
                                </li>
                            @endforeach
                        </ul>
                    </div>
                    <div class="px-4">
                        <input type="text" name="todo" class="tdl-new form-control" placeholder="Write new item and hit 'Enter'...">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
0 likes
13 replies
jlrdw's avatar

Sounds like a good candidate for a server fetched partial.

martinbean's avatar

@Danny971 Livewire is still the perfect choice for situations like this: dynamic pages where portions are updated in response to events. It’s essentially AJAX under the hood as it makes server-side requests, then only replaces parts of the DOM that actually need updating.

Alternatively, if you still want to proceed with jQuery like it’s still 2012, then you can define portions of your Blade templates as “fragments”, and then fetch the fragments via AJAX and replace chunks of your HTML page.

jlrdw's avatar

@martinbean Just FYI Caleb the author of Livewire demos server fetched partials using fetch js and vue.

Danny971's avatar

@Snapey I have installed Live wire and got it to submit the task witgh live wire but im still haveing trouble refreshing the todo list asynchronously (in the background without having the whole page to refresh )

here is my code

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\todolist;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class TodoListLW extends Component
{

    public $taskName;
    public $taskStatus =[];

    protected $listeners = ['TaskAdded' => 'updateTaskList'];

    public function mount() {

        $this->tasks = todolist::all();
    }

   
    public function render()
    {
        $tasks = todolist::all();
        return view('livewire.todo-list-l-w', compact('tasks'));
    }



    public function updateTaskList() {
        $this ->tasks =todolist::all();
    }



     // this function will be used to create the task and store it in the db 
  public function createTask() {
    // Get the currently authenticated user
    $user = Auth::user();

    // Check if the user is authenticated
    if ($user) {
        $tasks =$this ->taskName;
     //   dd("look what we have here:", $tasks);
        // Create a new instance of todolist model
        $TODO = new todolist();

        $TODO->task_name = $tasks;
        $TODO->task_status = 0; // Default status is to be unchecked 
        $TODO->posted_by = $user->id; // Assign the user ID to the user_id column in the todolist table


      

        // Save the task to the database
        $TODO->save();
        $this->emit('taskAdded');

        if ($TODO) {

           
            $this -> emit('taskAdded');
           session()->flash('notification', ['type' => 'success', 'message' => 'Task was successfully added']);
          
         
        } else {
            session()->flash('notification', ['type' => 'error', 'message' => 'Error occurred while adding Task']); 
        } 
    } else {
        // Handle the case where the user is not authenticated
        session()->flash('notification', ['type' => 'error', 'message' => 'User not authenticated']);
    }

  
} 
}



<!-- todo-list-l-w.blade.php-->
<div wire:poll.1s>
    

    @foreach ($tasks ?? [] as $task)
  
                                <li>
                                    <label >
                                        <input type="checkbox" wire:model="taskStatus.{{$task -> id}}"  wire.keydown.enter="createTask" data-task-id="{{ $task->id }}" {{ $task->task_status ? 'checked' : '' }} >
                                        <i></i><span>{{ $task->task_name }}</span> <a href='#'  class="ti-trash"></a>
                                    </label>
                                </li>
                            @endforeach

                            <div class="px-4">
    <input type="text" name="todo" class="tdl-new form-control" placeholder="Write new item and hit 'Enter'..." wire:model="taskName" wire:keydown.enter="createTask">
</div>

                            </div>
     

                            @livewireScripts

                            <script>

document.addEventListener('livewire:load', function () {
            Livewire.on('taskAdded', function () {
                Livewire.emit('refreshLivewireComponent'); // Trigger a Livewire refresh
            });
        });

                            </script>
   
</div>


dashboard.blade.php

            <div class="col-xl-4 col-xxl-6 col-lg-6 col-md-12 col-sm-12">
    <div class="card">
        <div class="card-header">
            <h4 class="card-title">Todo</h4>
        </div>
        <div class="card-body px-0">
            <div class="todo-list">
                <div class="tdl-holder">
                    <div class="tdl-content widget-todo2 mr-4">
                        <ul id="todo_list" 
                            data-save-todo="{{ route('save-todo') }}" 
                            data-update-todo-status="{{ route('update-todo-status', ':id') }}"  >

                            <livewire:todo-list-l-w />
                           
                        </ul>

   
                   
                </div>
            </div>
        </div>
    </div>
</div>

Please or to participate in this conversation.