Authorize AJAX in Laravel's register.blade.php form

0

I'm using Laravel's methods for registering users, however I'd like to use Javascript and Ajax events in the form to add specific information according to the information selected in the combobox city. I already use this same code for another view of my project and it works normally, but in the registration form when I try to send the request it returns me with the 401 Unauthorized error.

Jquery

$("#cbx_setor").show();
  $("#lbl_setor").show();

  $("#cbx_setor option").each(function(){
    $(this).remove();
  });

  $("#cbx_setor").append("<option value=''>Selecione um setor</option>")

  var url = URL + "/adm/setor/consulta";
  var cidade = $("#cbx_cidade").val();

  $.post(url, {"_token" : TOKEN, "cidade" : cidade})
  .done(function(data){
      console.log(data);
      $.each(data, function(index, item){
        $("#cbx_setor").append("<option value='" + item.id + "'> " + item.nome +"</option>");
      });
  });

Element in form register.blade.php

<div class="form-group row" id="div_setor">
    <label for='nome' id='lbl_setor' class="col-md-4 col-form-label text-md-right">Setor</label>
    <div class="col-md-6">
         <select id='cbx_setor' class='form-control'> 

         </select>
    </div>
</div>

NOTE: I have already added a field previously and I have registered normally, only requests are blocked.

    
asked by anonymous 28.03.2018 / 15:35

1 answer

0

From what I saw in your code, you are not passing the token.

You can put this field by default in all request headers so just put this meta tag in your template (to follow in the other pages)

<meta name="csrf-token" content="{{ csrf_token() }}">

and also put in the javascript of your template

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

For more information, see: link

    
01.04.2018 / 03:48