37

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

7 Answers 7

148

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>');
Sign up to request clarification or add additional context in comments.

3 Comments

OK, It works now, Thanks, Actually I made a little change because Laravel escape the character %
Ooops you're right. What did you use instead of %?
I just changed it to another string like S_id_E
15

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;

Comments

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>

Comments

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

Comments

0

I am not sure if this is relavant even after 10 years.

This is how I solved it with laravel 11

let tmp_url = "{{ route("my_your_url",['param1'=>'value1','param2'=>'--v2','param3'=>'--v3','param4'=>'--v4']) }}";

let url = tmp_url
   .replace('--v2',$("#v2").val()) // u can get any javascript variable as well.
   .replace('--v3',$("#v3").val())
   .replace('--v4',$("#v4").val())
   .replace();

Comments

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

1 Comment

Its the same as @lukasgeiter solution!
-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}`,
        .
        .
        .
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.