Removing an item with Ajax upon page reload

After creating a small Ajax script to remove items from my database and view, I encountered an issue where the view was only updated after a reload when the item was removed.

I want to avoid reloading the entire page by using window.location.reload() in my success function. Is there a way to handle this so that the item is removed from the view without the need for a full page reload?

<script>
    $(document).ready(function() {
      $(".destroy-device").click(function(e) {
        e.preventDefault();
        var id = $(this).attr("data-id");
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            }
        });
        $.ajax({
            url: 'destroy/'+id,
            type: 'post',
            data: {_method: 'delete',
                    id: id},
            success:function(data) {
                console.log('success');
            }
        });
      })
    });
</script>

HTML:

<form method="post">
    <input type="hidden" name="_method" value="delete">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="hidden" name="id" value="{{ $deviceValue->id }}">
    <button type="button" class="btn btn-danger destroy-device" data-id="{{ $deviceValue->id }}" name="destroy_device">
        <span class="glyphicon glyphicon-trash"></span>
    </button>
</form>

Answer №1

Imagine you have a collection of items retrieved from a database and then trigger an ajax request to delete certain items from the database. Upon receiving the deleted items' ids in the ajax callback, you can proceed to remove them from the user interface:

HTML

<ul id="myList">
   <li data-item="1">Item one</li>
   <li data-item="2">Item two</li>
   <li data-item="3">Item three</li>
</ul>

jQuery

$.ajax({
   ...
   success: function(data) {
      // data --> Array of deleted items (data-item)
      if (data) {
         var list = $('#myList');
         for(var i=0;i<data.length;i++) {
            list.children('li[data-item="' + data[i] + '"]').remove();
         }
      }
   }
});

A similar approach can be taken with a table or any other UI component

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 there a specific reason why passing functions from Express.js to EJS is not as straightforward as passing other variables?

I have been developing a blogging application using Express, EJS, and MongoDB. While working on implementing pagination for the posts, I encountered an issue with passing newerPosts and olderPosts to the view. I am passing them in a similar way to how the ...

Utilize the $(#id).html(content) method to populate the following column with desired content

Here is a snippet of my HTML code: <div class="row margin-top-3"> <div class="col-sm-7"> <h2>NFTs</h2> <div class="table-responsive"> <table class="table table-bordered&qu ...

What is the most appropriate unit of measurement for creating a responsive design?

I am a beginner in the world of responsive design and I'm currently figuring out how to properly layout plugins on a website when viewed on smartphones. Here's an example: @media (min-width: 568px) { .musicPlayer{ width:600px; height:320 ...

I am facing an issue with my React/Redux API where it is not logging out correctly and displaying [[

As a beginner in the coding world, I've run into some challenges while working with a React/Redux API. Following along with Bucky Roberts' YouTube tutorial, I decided to replace his static names object with an API that I then integrate into my r ...

Expand the dimensions of the shinydashboard dashboard page

Currently, I am using shinydashboard and have formatted my ui code in the following way: ui = dashboardPage(skin="black", dashboardHeader(disable = T), dashboardSidebar(width=300), dashboardBody() ...

Instructions for adding a Key every time a user clicks the space Key within an Input field

I built a Movie Search Page with the OMDB API. My current issue is that the API returns an error when searching for a movie with more than one word because the API URL requires a + key between each word. I am looking for a way to automatically add the + ke ...

jquery events fail to trigger following the dynamic loading of new content

I have developed a voting system that utilizes images. When a user clicks on an image, it submits the vote and fades out before reloading using a PHP page. The issue I'm facing is that after the first submit, clicking on the images does not trigger an ...

Show each item in the list vertically, using a single unordered list but displaying them in

Is there a way to display list items vertically in multiple columns using only a single ul? I need the output to look like: a e i b f j c g d h Any suggestions on how to achieve this would be greatly appreciated. Thank you! ...

Discovering a website's console content using the "web-request" npm package

I recently added the web-request NPM package to my project with the goal of retrieving console messages from a specific website. However, I encountered an issue as I was unsure of how to achieve this. var result = await WebRequest.get('http://disco ...

Is it possible to retrieve the code behind property in JavaScript?

How can I incorporate a C# code behind property into a JavaScript alert(<%= someProperty%>);? I've been trying to make it work but it's not happening. Any suggestions on how to successfully include the codebehind property in the JavaScript? ...

Utilizing the If statement within AlertifyJS

Whenever I attempt to use an if statement in conjunction with Alertify, it doesn't seem to function properly. Could there be an error in my approach? var question = alertify.prompt("What is your name?", "Lenovo"); if (question === "Lenovo") { fu ...

Utilize the power of React to iterate through the array object

I'm relatively new to working with react, and I'm attempting to create dynamic content using the .map() method. This is the component code that I have: import React, { Component } from "react"; class DynamicContent extends Component { ...

In Safari, non-ascii characters are incorrectly stored in document.cookies as trash

Below is a snippet of JavaScript code that I am working with: wdata['account'] = {"value": $(input).val(), "title": "Номер карты получения"}; var r = { "ipayway": ipw_selected, "wpayway": wpw_selected, "amount_type" ...

What is the alternative to using echo when outputting HTML?

I am working on a function... $post_text .= '<div style="font-size: 15px; color: blueviolet">'; $post_text .= "<br>"; $post_text .= 'Text number 1.'; $post_text .= "<br>"; $post_text .= 'Text number 2.'; $po ...

An array containing numerous "case" triggers

var message = "hello [[xxx]] bye [[ZZZ]]" var result, re = /\[\[(.*?)\]\]/g; while ((result = re.exec(message)) != null) { switch (result[1].toLowerCase()) { case "xxx": console.log("found xxx"); br ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Saving NVD3 Cumulative Line Charts as Image Files: A Simple Guide

I have been using the NVD3 Cumulative Line Chart and it has been working perfectly for me. However, I am interested in saving the graph as an image, similar to capturing a screen. I attempted to use html2canvas but unfortunately, it did not save the image ...

What steps can be taken to fix a syntax error in a NodeJS express server code?

I am currently facing a syntax error in the code below, and I'm struggling to fix it. The specific error message is as follows: node staticapi.js /Users/v/Desktop/CS-Extra/EIP/A5/staticapi.js:123 res.status(200).send("Api is running") ...

Using AJAX and JQuery to update a MySQL database with form data seamlessly without the need for page refresh

Progress has been made on most of this project, but now I face a challenging task that I am unfamiliar with. How can I update my mysql database with form data without causing the page to refresh? It seems like AJAX and/or jQuery would be used for this purp ...

Arrange images in a stack format, scaling them based on their percentage

I'm curious about how to overlap images that are sized using a percentage value (in this case, 100%). If the images had a fixed width/height in pixels, I could easily adjust their positions with position:relative to stack them on top of each other. Ho ...