Use js function variable in route

I want to pass ID to my route via ajax but cant do that:

function test(id){
      ajax: {
      url: '{!!  route('routename', ['menu_id' => id]) !!}',
          type: 'POST'

It says Use of undefined constant id.
How can i use javascript variables to pass through route?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It is not possible to use javascript variables in PHP as server side code is executed before client side code. So you may assign JS variables to equal PHP variables but not the other way around. Check this out:

You have the following options:

  1. Instead of route parameters, you may use request parameters
  2. If you really want to use route parameters, you would have to store your routes in your JS code (e.g. if the route is{menu_id}, you may store the route variable as an absolute url like so: var route = or as a relative url like so: var route = /routename/ and then in the ajax request append the route parameter like so url: route + id

Method 2

I think you can do this :

function test(id){
   var Link = "{!! route('routename',['menu_id' => '']) !!}"+"/"+id;
      ajax: {
      url: Link,
      type: 'POST'

Method 3

You Can try this.

$(document).on('click', '.clickClass', function () {

            var id=$(this).val();
            var action = "{{ URL::to('yourroutehere') }}/"+id;


<a href="" class=" rel="nofollow noreferrer noopener"hreflink">Action</a>

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x