Ad

Laravel Resource Controller Destroy Gives Me Error With Ajax

- 1 answer

here's my code.

$('.btn-danger').click(function () {
        id=$(this).attr('id');
        alertify.confirm("Want to delete?", "It's not possible to turn back!",
            function () {
                $.ajax({
                    type: 'DELETE',
                    url: '/blog/'+ id,
                    success: function (msg) {
                        alert(msg)
                     if (msg){
                         $("item-"+id).remove()
                         alertify.success('Done!')
                     }
                     else{
                         alertify.error('There's an error!')
                     }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alertify.error('error var' + 'blog/'+id)
                        var msg = '';
                        if (jqXHR.status === 0) {
                            msg = 'Not connect.\n Verify Network.';
                        } else if (jqXHR.status == 404) {
                            msg = 'Requested page not found. [404]';
                        } else if (jqXHR.status == 500) {
                            msg = 'Internal Server Error [500].';
                        } else if (exception === 'parsererror') {
                            msg = 'Requested JSON parse failed.';
                        } else if (exception === 'timeout') {
                            msg = 'Time out error.';
                        } else if (exception === 'abort') {
                            msg = 'Ajax request aborted.';
                        } else {
                            msg = 'Uncaught Error.\n' + jqXHR.responseText;
                        }
                        alert(msg)
                    }
                })
            },
            function () {
                alertify.error('Deleting cancelled.')
            }
        )
    })

And Here's my route.

Route::namespace('AdminPanel')->group(function (){
Route::prefix('admin')->group(function (){
    Route::resource('blog','BlogController');
});

});

and here's my destroy method.

public function destroy($id)
{
    $blog = Blogs::find(intval($id));
    if ($blog->delete()){
        echo 1;
    }
    echo 0;
}

and here's my route list (for answer in this question):

https://prnt.sc/qzmitr

But everytime i tried to click delete and said ok, ajax cant go with success function. There is an error : "Requested page not found. [404]".

How can i solve this?

Ad

Answer

your URL url: '/blog/'+ id, not valid, & you need to pass _token

url:'{{ route('blog.destroy', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
Ad
source: stackoverflow.com
Ad