Laravel 5.4: AJAX request using route with JS variable?

0

I need to use a Laravel route within the AJAX request code. The way I mounted it does not work, but it does not work.

I believe the call of the variable ( servico ) is wrong, because I manually set a number like this: {{ route('getEsp',1)}} , and it 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);
     });
});
    
asked by anonymous 05.08.2017 / 15:22

1 answer

1

The problem is that the url generated with route('getEsp', ...) is processed on the server, while the servico variable is only available for the JS. One way to get around this is to generate the url of the route with some placeholder for JS to replace 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 it clear what happens, let's look at what is generated by the blade 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, JS will effectively replace the placeholder with the value of the servico variable selected by the user. Inspect the page source for the browser to see exactly what's going on!

    
05.08.2017 / 17:26