尝试通过AJAX调用PHP函数时出现500错误

时间:2017-08-11 10:11:54

标签: javascript php email http-status-code-500

我正在尝试在用户完成网络表单时发送触发器电子邮件。

但是我收到以下错误

enter image description here

感谢有关如何解决此错误的任何建议。

将调用php函数的JS文件

$(function() {
  $('.error').hide();
  $(".request_demo").click(function() {

  // validate and process form here
  $('.error').hide();
  var email = $("#email").val();
  if (email == "") {
    $("#email_error").show();
    $("#email").focus();
    return false;
  }

  var email = $("#email").val();

  var dataString = '<p><strong>Email: </strong> ' + email + '</p>';
  $.ajax({
   type: "POST",
   url: "/script/send.php",
   data: { data: dataString, senderAddress: email },
   success: function() {
     // show a success message to your visitors
     // clear input field values

     $("#email").val('');    
   }
  });
  return false;  
 });
});

PHP文件

<?php
  if( isset($_POST) ){

    $postData = $_POST;
    $mailgun = sendMailgun($postData);

    if($mailgun) {
     echo "Great success.";
    } else {
      echo "Mailgun did not connect properly.";
    }
 }

 function sendMailgun($data) {

   $api_key = 'xxxxxxx1234';
   $api_domain = 'our_domain';
   $send_to = 'some@email.com';

   // sumbission data
   $ipaddress = $_SERVER['REMOTE_ADDR'];
   $date = date('d/m/Y');
   $time = date('H:i:s');

   // form data
   $postcontent = $data['data'];
   $reply = $data['senderAddress'];  

   $messageBody = "<p>You have received a new message from the contact form on your website.</p>
         {$postcontent}
          <p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";

   $config = array();
   $config['api_key'] = $api_key;
   $config['api_url'] = 'https://api.mailgun.net/v2/'.$api_domain.'/messages';

   $message = array();
   $message['from'] = $reply;
   $message['to'] = $send_to;
   $message['h:Reply-To'] = $reply;
   $message['subject'] = "New Message from your Mailgun Contact Form";
   $message['html'] = $messageBody;

   $curl = curl_init();

   curl_setopt($curl, CURLOPT_URL, $config['api_url']);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
   curl_setopt($curl, CURLOPT_USERPWD, "api:{$config['api_key']}");
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
   curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
   curl_setopt($curl, CURLOPT_POST, true); 
   curl_setopt($curl, CURLOPT_POSTFIELDS,$message);

   $result = curl_exec($curl);
   curl_close($curl);
   return $result;
 }
?>

1 个答案:

答案 0 :(得分:1)

我不确定这会解决您的问题,但这可能会对您有所帮助。

  1. 请检查服务器期望的数据类型。在您的ajax请求中,您没有提到任何Content-Type。由于这是一个POST请求,jQuery会将表单数据视为默认的Content-Type。我可以看到你提供了一个JS对象作为数据,默认情况下它会在将请求发送到服务器之前转换为查询字符串。

  2. 如果您的服务器期望请求中有json有效负载,那么您需要对有效负载执行JSON.stringify()以将JS对象转换为JSON对象。 即。 data:JSON.stringify({data:dataString,senderAddress:email})