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>');     
                });
        });
    })

Answers:

Answer

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>');
Answer

Thanks lukasgeiter, you make my day. It works. Only must to change the replace 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 simple let the id string only

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>';
Answer

Best way to use route in ajax.


Add route in hidden input or take as a attribute into the button or link. Like below.

This will save the other jquery code like get id and pass into the url. It's simple just get the url from input and pass as a URL. That's it.

<a data-url="{{ route('delete.PendingPatient',['id' => $u->id]) }}" class="btn btn-xs btn-danger btn_delete"> Delete </a>

Route

<?php

Route::delete('/pending_patient/{id}','[email protected]_patient'])->name('delete.PendingPatient');

jQuery

    <script type="text/javascript">
        jQuery(document).ready(function(){

          jQuery(document).on('click','.btn_delete',function(){
             var current = jQuery(this);
             var url = current.data('url');

             $.ajax({
                    url: url,
                    dataType:'json',
                    beforeSend:function() {
                        $('.stocks_list').html('Loading...');
                    }
                })
                .done(function(data) {
                    $('.stocks_list').html('<ul>');
                });

              });

         });
     });
</script>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.