简体   繁体   中英

Ajax remove item after reload

So I created a little Ajax script which removes items from my database and view, unfortunately the view does only Change after a reload (item gets removed).

I could do a window.location.reload() in my success function, but I do not want to reload the whole page.

How do I handle this so that I do not have to reload the whole page and the item gets removed in the view.

<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>

Suppose you have a list of items (loaded from database) and you execute an ajax call to delete some of those items from the database. You can return the deleted items' ids into the ajax callback and delete them from the UI:

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();
         }
      }
   }
});

You can do something similar with a table or another UI element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM