arslanmohsin420's avatar

Utilizing JavaScript Variables in Laravel Routes

When implementing a search functionality that dynamically retrieves user data, you may want to create buttons that link to specific Laravel routes using JavaScript variables. This process can be straightforward but requires careful handling of the variable values. Here’s how to achieve this using jQuery and Laravel's routing system.

Suppose you have a search feature that fetches user data and generates buttons for each user entry. Each button should navigate to a specific Laravel route, passing the user's ID as a parameter when clicked. Below is an example of how you can implement this functionality:

$('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 userId = value.id;  // Capture the user ID
            // Use template literals to insert the user ID directly into the route
            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" href="{{ url('show') }}/${userId}">
                                    <b class="fas fa-info"></b> <b>VIEW INFO</b>
                                </a>
                            </td>
                         </tr>`;
            
            $('#dynamic-row').append(tableRow);
        });
    }
});

});

0 likes
0 replies

Please or to participate in this conversation.