j_watson's avatar

How to use javascript variable in a laravel route?

I have a search function that returns the basic data of a user along with a generated button that should call a laravel route with the returned ID(value.id) as parameter when clicked. How do I use the value.id as a laravel parameter?

I tried creating a variable $newId and using it as a parameter but it doesn't work...

$('body').on('keyup','#search',function(){
        var keyword = $(this).val();

        $.ajax({
            type: "POST",
            url: "{{ route('search')}}",
            dataType: "json",
            data: {keyword: keyword,
                    _token: '{{csrf_token()}}'
            },
            success: function(res){
                var tableRow='';

                $('#dynamic-row').html('');

                $.each(res, function(index, value){
                    var $newId = value.id;
                    tableRow = '<tr><td><b style="color: #bb2124">'+value.id+'</b></td><td>'+value.fname+' '+value.lname+'</td><td>'+value.contactNo+'</td><td><a class="btn btn-outline-success" id="viewUserId" href="{{ route("show", '+$newId+') }}"><b class="fas fa-info"></b> <b>VIEW INFO</b></a></td></tr>';
 
                    $('#dynamic-row').append(tableRow);

                });
            }
        });
    });

0 likes
8 replies
jlrdw's avatar

It should be part of the request parameters. You have a post, not a get.

j_watson's avatar

I mean this part of the code.

href="{{ route("show", '+$newId+') }}"
piljac1's avatar

Assuming this is in a Blade file and that your route name exists, you would need to store your route in a variable with something like this

var showRoute = "{{ route('show', ':id') }}";

And then you replace :id with the actual value using replace

showRoute.replace(':id', $newId)
3 likes
Snapey's avatar

@RahimRahimi the solution lies in the fact that php variables and functions ( eg route()) are only executed on the server. Nothing you do in javascript can affect that.

Saif7amed's avatar

@RahimRahimi use @piljac1 answer, here is the final code:

var showRoute = "{{ route('show', ':id') }}".replace(':id', $newId);

tableRow = '<tr><td><b style="color: #bb2124">'+value.id+'</b></td><td>'+value.fname+' '+value.lname+'</td><td>'+value.contactNo+'</td><td><a class="btn btn-outline-success" id="viewUserId" href="'+showRoute+'"><b class="fas fa-info"></b> <b>VIEW INFO</b></a></td></tr>';

Please or to participate in this conversation.