Adding a new item to a list using Ajax after a post request - focusing on layout design

I currently have an activity stream available for users to use, as well as a site-wide view. When a user posts an update, it displays a default bootstrap success alert. However, I have noticed that other websites slide down existing items and append the newest post to the top of the list.

Attempting to implement this feature myself, I am facing challenges in adding all the necessary styling. I have tried incorporating the required <div> tags that form one activity item in my feed, but with no success.

In short - Is there a way to use ajax to clone the current top activity item and add it to the top? This would improve the dynamism of the code and eliminate the need for CSS within the .js file.

jQuery(document).ready(function ($) {

    $('form#postActivity').submit(function (event) {
        event.preventDefault();

        $postActivityNow = $(this);
        var subject = $('#activity_subject').val();
        var message = $('#activity_content').val();

        var data = {
            'action': 'postAnActivity',
            'subject': subject,
            'message': message,
        }


        $.ajax({
            type: 'post',
            url: postAnActivityAjax.ajaxurl,
            data: data,
            error: function (response, status) {
                alert(response);

            },
            success: function (response) {
                if (response.success) {
                    bootstrap_alert.success('Activity Added');
                } else {


                    if (response.data.loggedIn == false) {
                        bootstrap_alert.warning('you are NOT logged in');
                        console.log('you are not logged in')
                    }
                    if (response.data.userExists == false) {
                        console.log(response);
                        bootstrap_alert.warning(response.data.alertMsg);
                        console.log(response.data.alertMsg)
                    }

                }

            }

        });
    });
});

Answer №2

If you're looking to duplicate an element, you can use jQuery.clone()

var duplicatedItem = $("#myDiv").clone();

To add it as the first child: jQuery.prepend()

$("#parentDiv").prepend(duplicatedItem);

Best, hotzu

Answer №3

In the history, I have successfully utilized $.prepend()

For further details, visit this link jquery append to front/top of list

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

How can I style radio input elements with CSS when using Material UI within a component?

When styling in CSS, I typically use input[type="radio"]:checked { color: #000}, however this expression is not valid in Material UI. In Material UI, I create rules using makeStyles like so: const useStyles = makeStyles(() => ({ text: { colo ...

The button refuses to navigate to a URL upon being clicked

Struggling with my JavaScript buttons. Currently, they are functioning flawlessly, but I am attempting to change my "Order Online" button into a link that opens a new window to a Menufy menu page. Unfortunately, I can't seem to crack the code on how t ...

Ways to differentiate between a thumbnail image and a detailed image

On my image-heavy gallery page, I am looking to utilize a thumbnail image that is pre-sized with a maximum width of 200px. The images themselves are quite large, often surpassing 2000 pixels on the longest side. Although I have been using the Bootstrap cl ...

Tips for customizing the base font size in a Bootstrap 4 template

My Java/Spring Boot webapp utilizes Thymeleaf HTML page templates and Bootstrap 4, with the foundation being a free Bootstrap 4 site template called 'Simple Sidebar': . The current setup is functioning smoothly for me. I am interested in adjusti ...

What is the best way to display multiple HTML files using node.js?

click here to see the image Here is my server.js file. Using express, I have successfully rendered the list.html and css files on my server. However, I am encountering an issue when trying to navigate from list.html to other html files by entering localho ...

AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background. If I try to delete the last row, it gets deleted but the color remains for the first row only (it sh ...

How can I use console.log to display a message when a variable reaches a specific value?

As a beginner coder, I am struggling to find the solution to this coding issue. Here is the code snippet that I have attempted: var X = "Angry"; if X = "Angry" console.log(X is Angry) After running this code, I encountered an error message specifically p ...

Tips on sending image information from node.js to an HTML5 canvas?

Currently in the process of developing a demo featuring a node.js C++ plugin, I encounter an issue with the conversion of an ARGB bitmap to RGBA format for HTML5 canvas integration. The performance of this conversion process is exceedingly slow, prompting ...

Animate the jQuery menu to slide both upwards and downwards, as well as shift the inner divs to the right

I'm facing a jquery issue and could use some assistance. I am trying to achieve the following: Add a class "active" to style tags when they are active. Slide up/down vertically within a div (#information - containing "About" and "Contact"). Slide le ...

Guide on sending a JSONArray from ajax to the controller

Currently working with Spring MVC in Java, I am faced with an issue where I am attempting to pass a List from JavaScript to the controller as a JSONArray. However, upon reaching the controller, it is either showing up as an empty array or null. Would grea ...

Exploring the for... in loop for iteration in JavaScript

I am facing an issue with populating an empty array named objToArray using a for-in-loop. The goal is to fill the array with numbers from a hash object checkObj, but only if the keys have values that are greater than or equal to 2. const checkObj = { ...

Any ideas on how to iterate over a jQuery object and save the data in an array?

I am currently working on creating jQuery objects and then comparing those objects to check if any two are similar in terms of their properties. My goal is to alert the user and prevent the page from posting if any similarities are found. However, I am e ...

Having trouble accessing jQuery function within WordPress

Why is there a ReferenceError: Error message that says "manualEntry is not defined," appearing while trying to use the code snippet below in a Wordpress environment? <a href="#" onclick="manualEntry()">hide</a> <script ...

Parsing through JSON information retrieved from an API

I am working with an API that provides data in two arrays, each containing a category. I need help iterating through and displaying these categories, specifically the ones for Arts and Entertainment. Any assistance would be greatly appreciated. Thank you ...

There was no AJAX action triggered after the session was invalidated

We have a specialized JavaServer Faces web application using Primefaces 4.0 in conjunction with CAS Single Sign On integration. An issue arises when a user attempts to perform an ajax action, such as clicking a p:commandButton, after their session has bee ...

The value remains unchanged after performing JavaScript calculations and attempting to save it

I have multiple input fields on my form including expenses and a balance. Using JavaScript, I dynamically calculate the balance when any of the expense input fields are changed. Here's how: $(document).ready(function () { // sum up main number ...

Struggling to make antd compatible with my create-react-app project

Exploring ant.design with create-react-app piqued my interest, so I decided to follow the steps outlined in the antd documentation. https://ant.design/docs/react/use-with-create-react-app npx create-react-app antd-demo npm add antd Within the app.js fil ...

Storing and retrieving a client-side object in Javascript: A step-by-step guide

Novice inquiry: I have created a basic draggable to-do list that saves its state in a single object containing tasks, containers, and index - currently, it is being stored in local storage. I am now delving into server-side development using express and ...

Deliver XML document to client from an ASP.NET MVC webpage

I need help with an ASP.NET MVC web page that requires user input to create an XML file using a javascript function. After the user enters information and clicks a button, how can I display the XML created by the javascript method? In the .cshtml file: Fo ...

The live updates for user data in Firestore are not being reflected immediately when using valueChanges

Utilizing Angular and Cloud Firestore for my backend, I have a setup where users can follow or unfollow each other. The issue arises when the button text and list of followers/following do not immediately update on the front end after a successful click ev ...