Sounds like a good candidate for a server fetched partial.
Nov 25, 2023
13
Level 4
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>
Level 122
livewire
1 like
Please or to participate in this conversation.