Remove the JSON object from the screen in an asynchronous manner

I am currently working on developing a single-page application that retrieves information from a JSON file, displays it on the screen, and performs various actions.

At this point, all the information is being properly displayed on the screen: http://jsfiddle.net/rcsayf7t/3/

I am facing a challenge with the "Remove" button, as I need it to asynchronously remove the JSON object from the screen when clicked. Unfortunately, I am unsure of how to achieve this task.

HTML:

<table>
    <thead>
        <tr>
            <th scope="col"></th>
            <th scope="col">Name</th>
            <th scope="col">Message</th>
            <th scope="col">Date</th>
            <th scope="col"></th>
        </tr>
    </thead>
    <tbody class="tweets-result"></tbody>
</table>

jQuery:

// helper function for formatting date
function formatDate(date) {
    var dateSplit = date.split(" ");
    var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];

    // return the result
    return displayDate;
}


$(document).ready(function () {
    // start ajax request
    $.ajax({
        url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
        dataType: "text",
        success: function (data) {
            // store the JSON data
            var tweetData = $.parseJSON(data);

            // loop through json values and build the table
            $.each(tweetData.tweets, function (index, item) {
                $('.tweets-result').append(
                    '<tr>' +
                    '<td><img src="' + item.profile_image_url + '" alt="@' + item.screen_name + ' avatar"></td>' +
                    '<td><a href="https://twitter.com/' + item.screen_name + '">@' + item.screen_name + '</a></td>' +
                    '<td>' + item.text + '</td>' +
                    '<td>' + formatDate(item.created_at) + '</td>' +
                    '<td>Remove</td>' +
                    '</tr>');
                    
                    // WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
                    // ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
            });
        }
    });
});

Answer №1

Check out the live demo here

To remove a row, simply insert the following code inside the ajax success function:

$('.delete_row').click(function(){
      $(this).closest('tr').remove();
});

Make sure to add the following attribute in your HTML:

class="delete_row"

Here is the full Javascript code with comments included:

// Format date function
function formatDate(date) {
    var dateSplit = date.split(" ");
    var displayDate = dateSplit[0] + ", " + dateSplit[1] +  " " + dateSplit[2];

    // Return formatted date
    return displayDate;
}

$(document).ready(function() {
    // Make an ajax request
    $.ajax({
        url: "https://github.com/unique/tweets.json",
        dataType: "text",
        success: function(data) {
            var tweetData = $.parseJSON(data);

            // Loop through JSON data and build table rows
            $.each(tweetData.tweets, function(index, item) {
                $('.tweets-result').append(
                    '<tr>' +
                    '<td><img src="' + item.profile_image_url + '" alt="@' + item.screen_name + ' avatar"></td>' +
                    '<td><a href="https://twitter.com/' + item.screen_name + '">@' + item.screen_name + '</a></td>' +
                    '<td>' + item.text + '</td>' +
                    '<td>' + formatDate(item.created_at) + '</td>' +
                    '<td class="remove_row">Remove</td>' + 
                    '</tr>');
                
            });

            // Assigning click event for remove buttons
            $('.remove_row').click(function() {
               $(this).closest('tr').remove();
            });
        }
    });

});

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

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...

How to Align <ul> to the Right in Bootstrap 4

Looking to align a list to the right in the header section, here is the code snippet: <div class="collapse navbar-collapse" id="app-header-nav"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class=" ...

Transform a <td> into a table-row (<tr>) nested within a parent <tr> inside an umbrella structure

Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...

Implementing conditional reduction in JavaScript arrays

I've encountered an issue with the filter and reduce methods. I am attempting to calculate the sum of "smc" values only when "A" equals 2020 from the given array below: arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}] My attempted solution so ...

Combining strings in a JavaScript object

Can someone help me with concatenating strings within an object in JavaScript? I am parsing through an XML file to create a list of links in HTML. Each time I iterate through the loop, I want to add a new <li> element containing the link. How can I ...

Unable to retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, I’m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...

I have been experiencing issues with browserify when trying to use both jquery and jquery-ui

I have created a simple test app to showcase an issue I am facing. You can find the demo on this GitHub repository. In this demonstration, the first step was installing jquery and jquery-ui: npm install --save jquery jquery-ui Then I proceeded to creat ...

What is the best way to retrieve data from the state in react components?

After fetching data from my API using a getAll call, I stored all the values in this.state. However, I am struggling with extracting the arrays or objects from my state. Specifically, I am interested in retrieving the 'id' field from: 0: {id: 1, ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Angular HTTP post is failing on the first attempt but succeeds on the second try

Just started working on my first Angular exercise and encountered an issue where I am receiving an undefined value on the first attempt from an HTTP post request. However, on the second try, I am getting the proper response in Edge and Firefox. Thank you f ...

Tips for sending a file to a Servlet using an Ajax request

When working with an HTML form in AEM that requires file attachments, the challenge arises when trying to send these files via a Java Servlet through a Rest API. The issue lies in transmitting file arrays through Ajax to the Java Servlet, as only string da ...

Tips for circumventing the ajax data size restriction in asp.net mvc3

Currently, I am implementing an auto suggest function using AJAX in the following manner: $("#empName2").autocomplete({ search: function (event, ui) { var key = CheckBrowser(event); if (key == 13) return tr ...

Guide to uploading a JavaScript File object to Cloudinary via the node.js API

After researching various options, I decided to use cloudinary for uploading a file to an image server from my node js api. I successfully installed the npm package for cloudinary and implemented the code based on their api documentation Below is the fun ...

"Encountered a problem during the installation of pm2 for Node.js

I am in the process of installing pm2 (https://github.com/Unitech/pm2) Encountered the following error while doing so: D:\_Work>npm install pm2 -g --unsafe-perm npm WARN `git config --get remote.origin.url` returned wrong result (http://ikt.pm ...

What is the recommended data type to assign to the `CardElement` when using the `@stripe/react-stripe-js` package in TypeScript?

I'm struggling to determine the correct type to use for this import: import { CardElement } from '@stripe/react-stripe-js'; I have successfully used the types Stripe, StripeElements, and CreateTokenCardData for the stripe and elements props ...

Ways to retrieve every item in an array

I'm experiencing difficulty accessing the array of each object. Please review the response structure below. { "status": "1", "status_text": "Success", "current_page": 1, "next_page": "0", "previous_page": "0", "to ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

React JS project experiencing issues with Material UI components not functioning properly

Here is a unique version of my app.js code: import React from "react"; import './App.css'; import {Button} from "@mui/material"; function App() { return ( <div className="App"> <h1>COVID-19 T ...