How to pass javascript variable to laravel route on ajax call

You can pass javascript variable value to laravel route on ajax call. You have to use a placeholder to generate the URL and after that replace value by using replace method and pass the value to url parameters of ajax method.

Answers 1
  • Pass javascript variable value to laravel route on ajax call

    <script> 
    var id = $('#recordID').val();
    var url = '{{ route("deleteRecord", ":id") }}';
    url = url.replace(':id', id);
    //Call ajax
    $.ajax({
        type : "POST",
        url : url,
        success:function(response){
            console.log(response);
        }
    });
    </script>
    <!-- Laravel route definition and generated URL -->
    Route::post('/delete-record/{id}', [RecordController::class, 'delete'])->name('deleteRecord');
    <!-- #Generated URL -->
    http://localhost:8000/delete-record/1
    
    0

    You can pass javascript value to laravel route using replace method on url variable and assign to url parameter of ajax method.

  • Back to code snippet queries related jquery