Laravel 4, pass variable for routing in javascript

How to pass a variable (stock.id) from an Ajax response to a route to generate a URL for stock editing.

$.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>'); }); }); }) 
+7
javascript laravel laravel-4
source share
2 answers

You can first use a placeholder to create the url, and then replace it 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>'); 
+31
source share

Thanks Lucasgater, you make my day. It works. Just need to change the replacement method, because laravel scape ":" to "% 3A"

 var url = '{{ url("/admin/solicitud", ":id") }}'; url = url.replace('%3Aid', data.datos[i].id); dhtml+='<td><a href="'+url+'" class="btn btn-primary" role="button">Ver más...</a></td>'; 

or just just let the id string

 var url = '{{ url("/admin/solicitud", "id") }}'; url = url.replace('id', data.datos[i].id); dhtml+='<td><a href="'+url+'" class="btn btn-primary" role="button">Ver más...</a></td>'; 
+1
source share

All Articles