Authorize AJAX in Laravel’s Register.blade.php form

Asked

Viewed 95 times

0

I am using Laravel methods to register users, but I would like to use Javascript and Ajax events in the form to add specific information according to the information selected in the city combobox. 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 returns me with error 401 Unauthorized.

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 the formulary 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 performed the record normally, only requests are blocked.

1 answer

0

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

You can put this field to go by default in all request headers so just put this meta tag in your template (to follow on 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 on: https://laravel.com/docs/5.6/csrf

Browser other questions tagged

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