Laravel 5.4: AJAX request using route with JS variable?

Asked

Viewed 1,537 times

0

I need to use a route from Laravel within the AJAX request code. The way I built it doesn’t work, but it doesn’t work.

I believe the variable call (servico) you’re wrong, because I put a number manually this way: {{ route('getEsp',1)}}, and worked perfectly.

var servico = $('#servico').val();
var url = "{{ route('getEsp',"+servico+")}}";

$.get(url, function(data)
{
     $.each(data, function(index, subcatObj)
     {
          $('#especialidades').append('<input type="checkbox" name="id_especialidade[]" value="'+subcatObj.id+'">'+subcatObj.nomeEsp);
     });
});
  • It won’t work! you must pass the original url without server processing

  • Vish, I’ll have to think of another way to pass the url then. Thanks

1 answer

2


The problem is that the url generated with route('getEsp', ...) is processed on the server, while the variable servico is only available for JS. One way around this is to generate the path url with some placeholder for JS to replace it later. For example:

var servico = $('#servico').val();
var url = "{{ route('getEsp', '_servico_') }}".replace('_servico_', servico);

$.get(url, function(data)
{
     $.each(data, function(index, subcatObj)
     {
          $('#especialidades').append('<input type="checkbox" name="id_especialidade[]" value="'+subcatObj.id+'">'+subcatObj.nomeEsp);
     });
});

To make more clear what happens, let’s see what is generated by the Lade and the code delivered to the front-end.

// No arquivo .blade.php
var url = "{{ route('getEsp', '_servico_') }}".replace('_servico_', servico);

// O compilado do blade gera
var url = "<?php echo e(route('getEsp', '_servico_')); ?>".replace('_servico_', servico);

// O que o front-end recebe (imaginando um mapeamento para a rota)
var url = "http://www.site.com/especialidade/_servico_".replace('_servico_', servico);

From this point on, the JS will effectively replace the placeholder with the variable value servico user-selected. Inspect the page’s source code by the browser to see exactly what is going on!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.