I'm currently developing a task management application on the web. I have a textarea where users can input tasks, and when they press enter, it should automatically be added to a list element (li). The adding functionality works, but only after refreshing the webpage and sometimes having to do it twice.
Here's the JavaScript code:
var form = $('#add-form');
input = form.find('#text');
input.val('').focus();
form.on('submit', function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data){
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.appendTo('.list-group')
.css({ backgroundColor: '#1b7abd'})
.delay(200)
.animate({ backgroundColor: '#ffffff'});
input.val('').focus();
}
});
});
index.php
<?php $data = $database->select('items', ['id', 'text']); ?>
<form id="add-form" class="col-sm-12" action="_inc/add-item.php" method="post">
<p class="form-group">
<textarea action="add-new.php" class="form-control" name="message" id="text" rows="1" placeholder="Buy a milk, Go to the grocery shop..."></textarea>
</p>
</form>
add-task.php
<?php
// include
require 'config.php';
// add to the db
$id = $database->insert('items', [
'text' => $_POST['message']
]);
// success
if ($id) {
// header("Location: '. $site_url .'/index.php");
die('success');
}
?>
I've been trying to troubleshoot this issue for some time now without any success. The functionality used to work, but for some reason, it's not working now. I have linked both the JavaScript and jQuery files properly.