Is there a jQuery tool that can effortlessly add items to a list element?

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.

Answer №1

The issue stemmed from an error in the config.php file where a PHP package was likely causing interference with JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript has encountered an Uncaught TypeError due to an illegal invocation

I am currently developing a lambda function that calls another function with specific parameters. While this code runs without issues in Firefox, it encounters an error in Chrome, displaying a strange message in the inspector: Uncaught TypeError: Illegal ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Validate if the JSON data array contains any elements

I'm currently working with an ajax code and I need to determine whether the JSON data contains an array or not. However, despite my attempts, I am still receiving incorrect output. $.ajax({ url: url, type: 'POST', da ...

Working with Vue.js: Utilizing computed properties to iterate through a JSON data structure and generate a new

This is a computed property in Vue.js: shopCart() { var scart = [], group, node; scart.push({ payMethod: 0, transactionReference: "", RoomNumber: 0, addressId: 0, deliveryMinutes ...

Using hooks is restricted to the confines of a function component. An error will occur if they are called outside of this scope: "

How can I integrate a shopping cart feature into my app? I've created a separate file with the necessary functions, but I keep encountering an error related to invalid hook calls. export function CartProvider(props) { const [items, setItems] = u ...

The focus and blur events for the document in a content editable iframe are not activated by Chrome

As I modify the content of an iframe while it is in focus, I have noticed that this seems to function properly in Firefox. However, I am facing issues as the focus and blur events do not seem to trigger in Google Chrome! var iframe = $('#iframe') ...

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

Run a Python script to capture mouse coordinates using Selenium

Greetings, I am currently utilizing selenium webdriver to retrieve the X,Y coordinates of the cursor at a specific moment on the webdriver screen. However, I am facing challenges with the implementation of a method that involves using driver.execute_script ...

Make sure to pay attention to the messageCreate event within a direct message channel on discord

I've come across this question repeatedly, and despite trying numerous suggestions, I still can't seem to make it work. Currently, I'm resorting to logging the messageCreate event, but unfortunately, that isn't yielding any results. Any ...

How to relocate zeros to the end of an array using JavaScript without returning any value?

I'm currently working on a coding challenge from leetcode.com using JavaScript. I'm relatively new to algorithms and seem to be struggling with getting my initial submission accepted. The task at hand is as follows: Given an array nums, the goa ...

A variable must be defined within a specific block in order to be recognized

In an effort to enhance my code within a passport function, I am looking to pull values from a mongodb Database rather than from an array. The initial functioning code appeared as follows: passport.use( new LocalStrategy( { usernameField: ...

Chrome extensions using Cross-Origin XMLHttpRequest

Chrome extensions API states that cross-origin calls using the XMLHttpRequest object should be allowed with proper permissions: An extension can communicate with remote servers beyond its origin by requesting cross-origin permissions. Following the Goog ...

.NET MVC - Preventing Ajax.BeginForm from being compromised

I am facing security issues with an Ajax-based form in my .Net MVC Web Application. Despite implementing Google reCaptcha, the form is still vulnerable to hacks and spam messages. @using (Ajax.BeginForm("ContactSend", "Home", null, new ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

Tips for setting a uniform width for all bars in apexcharts bar column width

When working with dynamic data, the length of the data should also be variable. For instance, if the data has a length of 24, the column width should be 35px; similarly, even if the data has a length of 2, the column width should still be 35px. Apexchart ...

Learn how to run a Linux bash command by clicking a button, where the command is generated from user input

HTML: I am presenting two inputs here <input id="range3" type="range" min="0" max="255" value="0" /> <input id="num3" min="0" max="255&q ...

Having trouble importing from the src folder in Expo React

I am currently using expo-cli. When I import a module from the 'src' folder (which I created), it works perfectly fine when opened in a web browser, but encounters an error when opened on an Android device. I have tried using absolute paths and ...

It's incredibly frustrating when the Facebook like button is nowhere to be found

Currently, I am in the process of developing a website for a local bakery and have decided to incorporate a Facebook like button on the homepage. After visiting developers.facebook, I proceeded to copy and paste the code provided. It appears that there use ...

Leveraging the power of jQuery and vanilla JavaScript to create a pop-up print window for a Div element within a CMS platform that does not support media query stylesheets

I have been grappling with this particular issue for weeks now, seeking guidance from previous inquiries here. Yet, despite the helpful hints, I am still struggling to find a viable solution. My website features a scrolling sidebar measuring approximately ...

JavaScript function executes before receiving AJAX response

Within my code, there is an AJAX function named flagIt() that gets triggered by another function called validateForm() upon submission. The validateForm() function is responsible for form validation. function validateForm(){ var error = ""; //perf ...