0
I’m at the beginning of learning the Laravel along with ajax and I’m not able to pass data via post with ajax.
This is my ajax:
$(document).on('click', "#cad_academia", function(e){
e.preventDefault();
//var data = $("#new_gym").serialize();
var cnpj = $("#cnpj").val();
var academia = $("#academia").val();
var telefone = $("#telefone").val();
var email = $("#email").val();
var data = {
"cnpj" : cnpj,
"academia" : academia,
"telefone" : telefone,
"email" : email
}
$.ajax({
url: 'adicionar_academia',
dataType: 'html',
data: {data: data},
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
method: 'post'
}).done(function(msg){
alert(msg);
});
})
and this is the controller:
public function create(Request $data) {
$academia = $data->academia;
$telefone = $data->telefone;
$email = $data->email;
$cnpj = $data->cnpj;
$status = 3;
$plano = rand(0,2);
// Faz a verificação no banco se já existe o e-mail cadastrado
$verifica_email = DB::table('academias')->where('email', $email)->get();
$verifica_cnpj = DB::table('academias')->where('cnpj', $cnpj)->get();
$msg = '';
if(count($verifica_email) > 0) {
$msg = 'O e-mail informado já existe na nossa base de dados. Favor, escolher outro e-mail para efetuar o cadastro';
return view('criar', compact('msg'));
} else if(count($verifica_cnpj) > 0){
$msg = 'O cnpj informado já existe na nossa base de dados. Favor, escolher outro cnpj para efetuar o cadastro';
return view('criar', compact('msg'));
} else {
$dados =
[
'academia' => $academia,
'email' => $email,
'telefone' => $telefone,
'status' => $status,
'cnpj' => $cnpj,
'plano' => $plano,
'created_at' => date('Y-m-d')
];
DB::table('academias')->insert($dados);
$msg = 'Cadastro realizado com sucesso!';
return view('criar', compact('msg'));
}
}
I read, even here in stackoverflow that it is necessary to pass the csrf in the headers of the ajax request but even passing I can not get the expected result. Appears the code 419.
Error? If yes, say which pff
– Miguel
As I mentioned, it returns code 419 not completing the post request via ajax. Get goes normal, just in the post I’m not getting to have the same result even past the token in the ajax call.
– user60485
Maybe this solution will help, https://stackoverflow.com/a/46493409/3162303
– Miguel