Ajax调用PHP成功触发错误

时间:2015-01-15 18:10:00

标签: php ajax email

我正在调用PHP函数来发送包含表单信息的电子邮件,电子邮件正在成功发送和接收,当我调试PHP函数时,它返回TRUE。问题是AJAX调用正在捕获[object Object]错误,它会在AJAX调用的错误部分触发函数而不是成功调用。有谁知道这可能导致什么?

这是我的Java脚本代码:

<script type="text/javascript">
$("#candidate_form").submit(function(){


$.ajax({
    type: "POST",
    url: "php/mail.php",
    data: { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val(), phone: $("#phone").val()},
    dataType: "json",
    success: function(response){
      alert(response)
      $("#jobModal").show();
    },
    error: function(response){
      alert("This action failed with the following error" + response);
    }
  })
  .done(function(data) {
    $("#jobModal").modal("show");
  })


});

</script>

这是我的PHP代码:

<?php


if (isset($_POST)) {
sendCandidate();
} 

function sendCandidate() {

 $emailTo="mail@gmail.com";
 $subject="Candidate Info Submited from Website";
 $body= "Hello!

A new candidate has submited his/her information from our website. Please check the candidate´s     information and contact him/her as soon as possible.

 Name: ". $_POST['fname']. " ". $_POST['lname']. 
 "
 Email: ".$_POST['email']. 
 "
 Phone: ". $_POST['phone'].
 "

Regards!

--
Jobs 
 ";
 $headers="From: candidates@jobs.com";

 #Sending mail with candidate´s info to recruiters.
 $candidateMailSent = mail($emailTo, $subject, $body, $headers);


 #Sending thank you email to candidate.
 mail($_POST['email'], "Jobs - Resume submited",
 "Hello ". $_POST['fname']." ". $_POST['lname']. ","."

We really appreciate your interest in working with us towards getting your new job. We have received your Resume and Contact Information and one of our Specialized Recruiters     will be getting in touch with you as soon as possible.

If you have any doubts please feel free to contact us by sending an email to     contact@jobs.com with the Subject: Candidate Inquiry.

Regards!

--
Jobs


 ", $headers);





 return json_encode($candidateMailSent);
}



?>

1 个答案:

答案 0 :(得分:0)

首先,当你执行json_encode时,需要在数组上完成。 Mail返回您分配给$candidateMailSent的布尔值。您应该将其分配给$candidateSentMail['success']

在邮件的php文档中,它表示返回值为true或false。我没有看到它返回了一条消息。

然后在jquery方面,您将测试响应为responce.success

例如,

   success: function(response.success){
      alert(response.success)
      $("#jobModal").show();
    },
    error: function(response.success){
      alert("This action failed with the following error" + response.success);
    }