Search code examples
ajaxlaravellaravel-routing

how can i set url of route from AJAX


WEB (route) :

Route::get('/ajax-cat/edit/{id}', [App\Http\Controllers\AjaxCRUDController::class, 'categoryEdit'])->name('ajax.categoryEdit');

AJAX Code:

    $(document).ready(function () {
    $("#categoryBtn").click(function () {
        $("#catTable").show();
        let html = '';
        let i = 0;
        $.ajax({
            url: '/ajax-cat',
            type: "GET",
            success: function (data) {
                for (const x of data) {
                    html += `<tr>
                                <th scope="row">${++i}</th>
                                <td>${x.name}</td>
                                <td><a href="{{route('ajax.categoryEdit',${x.id})}}" class="btn btn-danger">Edit</a></td>
                            </tr>`;
                }
                $("#catTableBody").html(html);
            }
        });

    });
});

Picture from Browser:

enter image description here

But I want Link like this: 127.0.0.1:8000/ajax-cat/edit/2


Solution

  • You cannot merge different language syntax like this.

    {{ }} is from Blade Directive. https://laravel.com/docs/8.x/blade

    x.id
    

    is a variable defined in your javascript code block.

    What you can do is:

    var url = '{{route("ajax.categoryEdit", ":id")}}';
    url = url.replace(':id', x.id);
    

    Then you can concat your javascript variable inside your html code.