In my web application, I have set up a form with a textarea and a button. Upon submission, I prevent the default action using e.preventDefault() and submit the form via AJAX. The returned query is then prepended as information inside a div at the top of a list.
Additionally, each item has the ability to be deleted instantly on the client side and also through an AJAX call for complete removal. While this functionality is mostly working, there are some issues.
Current Functionality:
- Creating and deleting a single item works fine
- Adding two items, then deleting the newest item works fine, but trying to delete the oldest item results in an error. It attempts to delete itself along with the newest item, leaving the second item alone.
What Needs to Be Done:
- Ensure that newly prepended elements inherit the event handler
- Delete only the selected item without affecting others
Code Explanation:
When the page loads, items from the database are queried and displayed on the screen.
In the provided JavaScript code snippet, you can find the function delPostFunc which handles deletion of posts. This function is immediately called to assign click event handlers to existing items upon initial load.
For submitting a new item, the code attaches event listeners to handle the submission process via AJAX. The returned data (newest post) is prepended to the list, and the event handler is reassigned to include the newly added item.
Javascript Code Snippet:
// Specific functions related to post deletion and submission
// These functions utilize promises and AJAX requests
// GET Request Function
const get = (url) => {
// Promise implementation for HTTP GET request
}
// Delete Post Promise Function
const deletePostPromise = (url, postId) => {
// Promise implementation for post deletion via AJAX
}
// Submit Post Promise Function
const submitPost = (url, userId, userName, content) => {
// Promise implementation for submitting a new post via AJAX
}
// Return Newest Post Promise Function
const returnNewestPost = (url) => {
// Promise implementation for retrieving the newest blog post via AJAX
}