Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4, Pass a variable to route in javascript

How Can I pass the variable (stock.id) return from Ajax response to the route to generate the url to edit a stock

$.ajax({             url: 'sectors/stocks/' + $(this).data('sector-id'),             dataType:'json',             beforeSend:function() {                 $('.stocks_list').html('Loading...');             }         })         .done(function(data) {             $('.stocks_list').html('<ul>');             $.each(data, function(index, obj_data) {                 $.each(obj_data.stocks, function(indx, stock) {                     $('.stocks_list').append('<li><a href="{{route("admin.stocks.edit","'+stock.id+'")}}">' + stock.symbol + ' </a></li>');                      });         });     }) 
like image 789
Marwan Avatar asked Dec 24 '14 09:12

Marwan


2 Answers

You can first use a placeholder to generate the URL with and then replace that in javascript.

var url = '{{ route("admin.stocks.edit", ":id") }}'; url = url.replace(':id', stock.id); $('.stocks_list').append('<li><a href="'+url+'">' + stock.symbol + ' </a></li>'); 
like image 120
lukasgeiter Avatar answered Sep 25 '22 10:09

lukasgeiter


In my opinion the simplest way is by concatenating javascript variable with blade string as follows.

Case 1: Route paramter is required

In this case pass the empty string in place of route parameter to by pass the required validation.

var url = "{{route('admin.stocks.edit', '')}}"+"/"+stock.id; 

Case 2: Route paramter is optional

In this case you do not have to pass the empty string.

var url = "{{route('admin.stocks.edit')}}"+"/"+stock.id; 
like image 38
fahad shaikh Avatar answered Sep 24 '22 10:09

fahad shaikh