简体   繁体   中英

Laravel Route call via AJAX gets wrong URL 404 (Not Found)

I have the following route defined in my web.php

Route::delete('/contributions/contribution/destroy', 'ContributionController@destroy');

In my blade file I have a button that when clicked displays a sweetalert to confirm deletion. This works correctly, but when the user presses the delete button instead of it going to the URL defined in Ajax it goes to an incorrect URL and logs the following error:

jquery.min.js:4 DELETE http://localhost/contributions/batches/batch/edit 404 (Not Found)

Here is button code

<td class="text-center"><button type="button" class="btn btn-danger btn-sm btn-icon btn-destroy" 
                                                    data-batch-id="{{ $batch->id }}" 
                                                    data-id="{{ $contribution->id }}" 
                                                    data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
                                                    data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"
                                                ><i class="fa fa-times"></i></button>
                        </td>

Here is my script

<script>

$(document).on('click', '.btn-destroy', function (e) {
    e.preventDefault();
    var batchId = $(this).data('batch-id');
    var id = $(this).data('id');
    var amount = $(this).data('amount');
    var contributor = $(this).data('contributor');
    swal({
            title: "Delete?",
            text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
            type: "error",
            showCancelButton: true,
            confirmButtonClass: 'btn-danger',
            confirmButtonText: "Delete",
            closeOnConfirm: false
        },
        function() {
            $.ajax({
                url: "{{ url('/contributions/contribution/destroy') }}",
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                type: "DELETE",
                data: {batch:batchId, contribution:id},
                success: function (data) {
                    console.log(data);
                    }               
            });
    });
});

oddly enough, refreshing the page after the error returns my session flash message from my controller's destroy function

*Note: I did add the DELETE verb to IIS, before this I was receiving:

405 (METHOD NOT ALLOWED)

Any ideas?

Try this style of ajax

$.ajax({
        url: "{{ url('/contributions/contribution/destroy') }}",
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
       'data':{
         '_method':'delete',
          '_token':'{{ csrf_token() }}',
       },
       'method':'post'
});

After two days of reading and wrenching I have a working solution:

route:

Route::delete('/contributions/contribution/destroy', 'ContributionController@destroy');

link html:

<a href="#" class="btn btn-danger btn-sm btn-icon btn-destroy" 
      data-id="{{ $contribution->id }}" 
      data-amount="${{ number_format ($contribution->contribution_amount, 2, '.', ',') }}"
      data-contributor="{{ $contribution->first_name.' '.$contribution->last_name }}"><i class="fa fa-times"></i></a>

jquery/ajax:

<script>

    $(document).on('click', '.btn-destroy', function (e) {
        e.preventDefault();
        var contributionId = $(this).data('id');
        var amount = $(this).data('amount');
        var contributor = $(this).data('contributor');
        swal({
                title: "Delete?",
                text: "Do you want to delete contribution for "+ amount +" from "+ contributor +"?",
                type: "error",
                showCancelButton: true,
                confirmButtonClass: 'btn-danger',
                confirmButtonText: "Delete",
                closeOnConfirm: false
            },
            function() {
                $.ajax({
                    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                    method: "DELETE",
                    url: "{{ url('/contributions/contribution/destroy') }}",
                    data: {contributionId:contributionId},
                    success: function (msg) {
                        if ( msg.status === 'success' ) {
                            swal("Deleted", msg.msg, "success");
                            setInterval(function() {
                                window.location.reload();
                            }, 3900);
                        }
                    },              
                    error: function(msg) {
                        swal("Error!", "Something went wrong.", "error");
                        console.log(msg.status);
                    }
                });
        });
    }); 

</script>

controller:

public function destroy(Request $request)

{
    if ( $request->ajax() ) {

        Contribution::find($request->contributionId)->delete();

        return response(['msg' => 'Entry deleted', 'status' => 'success']);
    }
    return response(['msg' => 'Failed deleting the entry', 'status' => 'failed']);        
} 

Works perfectly!

删除小牛

确认书

in my case I removed the error by running simple classic:

php artisan route:clear

or you can launch that remotely. Create a route and a Controller and call it via browser link:

Route::get('/b/{x}',  'for_stuff\BController@kukuku');

and put into the controller's function:

Artisan::call('route:clear');

say:

https://mysite/b/r

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