Search code examples
javascriptphplaravellaravel-9

What is the proper way of passing js variable to encoded route


I have this script at my Blade:

<script>
function getComboA(selectObject) {
    var value = selectObject.value;  
    window.location.href = {!! json_encode(route('changeRequestStatusNhd', value)) !!}
}
</script>

Basically, the variable value holds the value of select option input and I need to pass this variable to the route changeRequestStatusNhd as its a parameter.

But the way I pass it in route('changeRequestStatusNhd', value) is wrong (Use of undefined constant value - assumed 'value' (this will throw an Error in a future version of PHP))!

But I don't know what is the proper way of passing this js variable to laravel route...

So if you know, please let me know..

Thanks


Solution

  • <script>
    function getComboA(selectObject) {
        var value = selectObject.value;
        var route = "{{ route('changeRequestStatusNhd') }}"; // it will be rendered when page load.
        window.location.href = `${route}/${value}`
    }
    </script>
    

    Laravel's Variables and function will rendered on page load. So it is not possible to bind the Javascript variables on specific events.