PHP无法从jQuery的serialize()中检索数据

时间:2017-11-28 19:21:18

标签: php jquery ajax wordpress

我正在尝试通过Wordpress的原生PHPMailer类和Ajax发送包含联系信息的电子邮件。这是相关的代码:

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="contato@empresa.com.br">contato@empresa.com.br</a> .
  </div>
</form>

Ajax将数据发送到Wordpress的调用PHPMailer的functions.php文件中的函数。在初始化PHPMailer之前,我正在检索这样的ajax数据:

$nome = trim($_POST['name']);
$mensagem = trim($_POST['comments']);
$email = trim($_POST['email']);

然后尝试将其打印到电子邮件正文中:

    $mail->Body = "Nome: " . $nome . "\nE-mail: " . $email . "\nMensagem: " . $mensagem;

PHP正确执行这些功能,我收到测试电子邮件,但它没有从Ajax调用接收数据。控制台显示序列化数据,这意味着没有错,但不知何故它没有到达PHP脚本。我怀疑它与Wordpress有关。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您的newCustomerForm需要data中的密钥:

data: {
   action: 'sendmail',
   custForm: newCustomerForm
}

在PHP文件中,您需要解析custForm字符串:

parse_str($_POST['custForm'], $form);
//Then access the custForm data using $form, e.g. $form['name']