When a request is made ajax
in laravel
must take into account some very important aspects such as:
When the request is post: You should always send the variable _token
with the data csrf_token()
generated by laravel per logged in user, in case the request is < strong> get "is not mandatory if recommended".
The url
must be well written, writing on blade labels is best for example: {{url("/empresas")}}
or {{route("empresa.store")}}
, this in case the script
is in a file .blade.php , in case the script
is in a .js file, you should look for solutions such as creating a global variable ex: var url_global="{{url('/')}}";
and use this variable in its url
's ajax, Ex: url:url_global+"/empresa"
.
Applying what you explain, the following might work for you:
$("#Enviar").click(function (e) {
e.preventDefault();
var nombre = $('#name').val();
var nombre = $('#display_name').val();
var token = '{{csrf_token()}}';// ó $("#token").val() si lo tienes en una etiqueta html.
var data={nombre:nombre,_token:token};
$.ajax({
type: "post",
url: "{{route('empresa.store')}}",// ó {{url(/admin/empresa)}} depende a tu peticion se dirigira a el index(get) o tu store(post) de tu controlador
data: data,
success: function (msg) {
alert("Se ha realizado el POST con exito "+msg);
}
});
});
Route::resource('empresas', 'EmpresaController');
Keep in mind that when you make a group
in your routes
and you put a prefix , your url is lengthened, in your case they will be like these:
_____________________________________________________________________
Url | Method | Route
_____________________________________________________________________
tupagina.dev/admin/empresa | get |empresa.index
tupagina.dev/admin/empresa | post |empresa.store
tupagina.dev/admin/empresa/create | get |empresa.create
tupagina.dev/admin/empresa/{empresa} | get |empresa.show
tupagina.dev/admin/empresa/{empresa} | put |empresa.update
tupagina.dev/admin/empresa/{empresa} | delete |empresa.destroy
tupagina.dev/admin/empresa/{empresa}/edit | get |empresa.edit