ajaxlaraveldelete-method

Laravel Ajax can't pass parameter in url but works with a constant


I'm writing an ajax that works when url contains a constant but does not work when url contains a variable because this does not get replaced by the actual value.

$('body').on('click', '.deleteLayer', function () {
        var layer_id = $(this).data('id');
        confirm("Are You sure want to delete record with layer_id="+layer_id+"?");

        $.ajax({
            type: "POST",
            url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
            data: {_method: 'delete', layer:layer_id},
            success: function (data) {
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

  });

If I use a value, let's say 50 instead of layer_id then it works!!!:

 url: "{{ route('layers.destroy',['layer' => 50])}}",

This is the route that I try to access:

DELETE | admin/layers/{layer} | layers.destroy   

If I do not send layer parameter in the url I receive the following error

message : "Missing required parameters for [Route: layers.destroy] [URI: admin/layers/{layer}]. (View: /var/www/laravelapp/resources/views/layers.blade.php)"

Why is layer_id, here

 url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}", 

not replaced by the actual value?


Solution

  • When you are writing like ['layer' => "+layer_id+"] the js variable is not working. It goes like +layer_id+ as the parameter of the route. You can try like this

    var layer_id = $(this).data('id');
    var url = '{{ route("layers.destroy", ":id") }}';
    url = url.replace(':id', layer_id );
    $.ajax({
        type: "POST",
        url: url,
        data: {},
        success: function (data) {
    
        },
        error: function (data) {
    
        }
    });