通过Ajax删除图像而无需重新加载页面Laravel

时间:2018-08-07 13:25:45

标签: php ajax laravel

我想删除图像而不通过Ajax重新加载页面,但是每次删除图像时,首先它都不会被删除,但是当我刷新页面时,图像可以删除。

app.js:

$('.delete-image').on('click', function(e){
    e.preventDefault();
    let id = $(this).attr('data-id');
    bootbox.confirm("Are you sure you want to delete this company?", function(result){
        if(result){
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type : 'DELETE',
                url : '/albums/delete',
                data : {
                    id : id,
                },
                success : function(response){
                    if(response){
                        $(this).parents('.album').slideUp().remove();
                    }
                }.bind(this)
            })
        }
    }.bind(this));
});

AlbumController:

public function deleteImage(Request $request){
        $album = Album::find($request->id);
            if($album->delete())
                return response()->json(true);
            else
                return response()->json(false);
    }

blade.php:

@extends('layout.app')

@section('content')
    <div class='medium-3 columns end'>
        <div class="row text-center">
            @foreach($album as $albm)
                <h4>{{$albm->name}}</h4>
                <h4>{{$albm->description}}</h4>
                <a href="/albums/{{$albm->id}}" class="btn btn-link">Edit
                    <img class="thumbnail" src="/storage/store/{{$albm->cover_image}}" alt="{{$albm->name}}">
                </a>
                <a href="" class="btn btn-link delete-image" data-id="{{$albm->id}}">Delete</a>
                <br>
            @endforeach
        </div>
    </div>
@endsection

路线:

Route::delete('/albums/delete', 'AlbumController@deleteImage');

2 个答案:

答案 0 :(得分:1)

$(this).parents('.album').slideUp().remove();

您没有带有class="album"的元素,因此选择器不匹配任何内容。

答案 1 :(得分:0)

删除成功响应后,只需删除其父类div的父级row

$('.delete-image').on('click', function(e){
    e.preventDefault();
    let id = $(this).attr('data-id');

    let parentDiv = $(this).closest('div.row');

    bootbox.confirm("Are you sure you want to delete this company?", function(result){
        if(result){
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                type : 'DELETE',
                url : '/albums/delete',
                data : {
                    id : id,
                },
                success : function(response){
                    if(response){
                        $(parentDiv).remove();
                    }
                }.bind(this)
            })
        }
    }.bind(this));
});