I'm trying to send an e-mail with contact information through Wordpress's native PHPMailer class and Ajax. Here's the relevant code:
jQuery(document).ready(function() {
jQuery('#formContato').submit(ajaxSubmit);
function ajaxSubmit() {
var newCustomerForm = jQuery('#formContato').serialize();
jQuery.ajax({
type: "POST",
url: "<?php echo site_url(); ?>/wp-admin/admin-ajax.php",
data: {
action: 'sendmail',
newCustomerForm
},
success: function(data) {
jQuery("#alertaOk").show();
console.log(data);
console.log(newCustomerForm);
},
error: function(errorThrown) {
jQuery("#alertaErro").show();
console.log(errorThrown);
}
});
return false;
}
});
#alertaOk {
display: none;
}
#alertaErro {
display: none;
}
<form id="formContato" method="post">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form-control" id="name" name="name" placeholder="Nome" type="text" required>
</div>
<div class="col-sm-6 form-group">
<input class="form-control" id="email" name="email" placeholder="E-mail" type="email" required>
</div>
</div>
<textarea class="form-control" id="comments" name="comments" placeholder="Mensagem" rows="5"></textarea><br>
<div class="row">
<div class="col-sm-12 form-group">
<button class="btn btn-default pull-left btn-laranja" type="submit">Enviar</button>
</div>
</div>
<div id="alertaOk" class="alert alert-success">
<strong>Obrigado!</strong> Recebemos sua mensagem e entraremos em contato em breve.
</div>
<div id="alertaErro" class="alert alert-danger">
<strong>Algo deu errado.</strong> Nossos administradores já foram avisados, por favor envie sua mensagem para o e-mail <a href="[email protected]">[email protected]</a> .
</div>
</form>
The Ajax sends the data to a function in Wordpress's functions.php file that calls PHPMailer. Before initializing PHPMailer I'm retrieving the ajax data like this:
$nome = trim($_POST['name']);
$mensagem = trim($_POST['comments']);
$email = trim($_POST['email']);
and then trying to print it into the email's body:
$mail->Body = "Nome: " . $nome . "\nE-mail: " . $email . "\nMensagem: " . $mensagem;
PHP executes the functions just right, I receive the test emails, but it's not receiving the data from the Ajax call. The console is showing the serialized data, which means that it's not wrong, but somehow it's not reaching the PHP script. I suspect it's something related to Wordpress.
Thanks in advance.