Laravel 4, Pass a variable to route in javascript
Asked Answered
B

6

35

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>');     
                });
        });
    })
Babyblueeyes answered 24/12, 2014 at 9:7 Comment(0)
I
145

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>');
Implantation answered 24/12, 2014 at 9:12 Comment(3)
OK, It works now, Thanks, Actually I made a little change because Laravel escape the character %Babyblueeyes
Ooops you're right. What did you use instead of %?Implantation
I just changed it to another string like S_id_EBabyblueeyes
A
16

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;
Algonquin answered 12/9, 2020 at 12:59 Comment(0)
S
6

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}','PatientController@pending_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>
Saponin answered 22/2, 2019 at 6:45 Comment(0)
D
4

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>';
Dumb answered 24/8, 2017 at 8:45 Comment(0)
Y
-1
let calculatedId = e.currentTarget.id.split("_")[1];

let url = '{{route('queryToggleStatus', ':queryId')}}';

url = url.replace(':queryId', calculatedId);

$.get(url, function(data, status) {
  console.log (data);
})
Yonkers answered 27/7, 2021 at 6:13 Comment(1)
Its the same as @Implantation solution!Leavings
P
-1

if is required param:

$("#program_id").change(function (e) {
    const $programId = $(this).val();
    $.ajax({
        url: `{{route('get-group-subjects-by-program', '')}}/${$programId}`,
        context: document.body,
        type: "GET",
        .
        .
        .
    });
});

If not required param:

$("#program_id").change(function (e) {
    const $programId = $(this).val();
    $.ajax({
        url: `{{route('get-group-subjects-by-program')}}/${$programId}`,
        .
        .
        .
    });
});
Pylos answered 21/3, 2024 at 13:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.