I'm trying to get Javascript to get the data sent by the server and play on the alert. But it always comes undefined. I have already looked at many topics on the internet and found nothing wrong with the code. In theory it was meant to work. Can someone help me? Thanks
Here is the JS code:
$(document).ready(function() {
$( "#enviar" ).click(function( event ) {
event.preventDefault();
var email = $('#email').val();
var nome = $('#nome').val();
var telefone = $('#telefone').val();
var msg = $('#msg').val();
$( "#cont-form" ).html('<div class="loader" id="load"><img src="img/loader.gif"></div>');
$.ajax({
url : '/send',
method : 'POST',
data : { msge: msg, mail: email, tel: telefone, name: nome, _token: token},
success: function(data){
$( "#cont-form" ).html('<div class="enviada"><h1>Mensagem enviada!</h1></div>');
$('.enviada').hide();
$('.enviada').slideDown();
alert(data.test);
}
});
});
});
Here is the part of the controller that receives the request:
public function enviar(Request $request) {
$msg = $request['msge'];
$nome = $request['name'];
$email = $request['mail'];
$telefone = $request['tel'];
if ($telefone == '') {
$telefone = 'Numero não informado';
}
$enviar = new Emails();
$enviar->enviarEmail($nome, $email, $telefone, $msg);
}
And finally the class that sends the email:
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Response;
class Emails extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
//
}
public function enviarEmail($nome, $email, $telefone, $msg)
{
$title = $nome;
$content = $msg;
$info = [
'nome' => $nome,
'email' => $email
];
Mail::send('emails.send', ['title' => $title, 'content' => $content, 'telefone' => $telefone], function ($message) use($info)
{
$message->from($info['email'], $info['nome']);
$message->to('[email protected]')->subject('Mensagem do Site');
});
return response()->json(['test' => 'Request completed']);
}
}