PHP脚本在本地工作但在ajax调用上我得到500内部服务器错误

时间:2017-08-31 22:12:31

标签: php ajax heroku

我有一个使用SendGrid发送电子邮件的php脚本。如果我摆脱$ _POST命令,手动设置值并在本地运行(从cmd)它可以工作。但是当尝试使用ajax提交表单时,我收到了500内部服务器错误。

这是php代码

<?php require 'vendor/autoload.php';
header("Access-Control-Allow-Origin: *");

if(!(isset($_POST['email']) && isset($_POST['messageType']) && isset($_POST['projectName']) && isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['message']))){
    echo "Unable to process request";
    return;
}

$email = $_POST['email'];
$type = $_POST['messageType'];
$project = $_POST['projectName'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$message = $_POST['message'];

$from = new SendGrid\Email($firstName . " " . $lastName, $email);
$subject = $type == "Message" ? "www.teodorvecerdi.me | " . $type : "www.teodorvecerdi.me | " . $type . " | " . $project;
$to = new SendGrid\Email("Teodor Vecerdi", "teodor.vecerdi@gmail.com");

$content2 = "<table><tr><td>Name</td><td>$firstName $lastName</td></tr><tr><td>Email</td><td>$email</td></tr>";
if($project != "I didn't select 'Suggestion for project'")
    $content2 .= "<tr><td>Project</td><td>$project</td></tr>";
$content2 .= "<tr><td>Message</td><td>$message</td></tr></table>";

$content = new SendGrid\Content("text/html", $content2);
$mail = new SendGrid\Mail($from, $subject, $to, $content);

$apiKey = 'API KEY';
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
print_r($response->headers());
echo $response->body();`

这是AJAX调用

$('#SendMessageForm').on("submit", function (e) {
   e.preventDefault();
   var data = $(this).serialize();
   $.ajax({
      url: 'https://sendemail-teodorvecerdi.herokuapp.com',
       type: 'POST',
       data: data,
       success: function (response) {
           console.log(response);
           console.log("Success");
       },
       fail: function (response) {
           console.log(response);
           console.log("Failure");
       }
   });
});

编辑:我在heroku上托管脚本

这是我提交表单时在日志中显示的内容:

2017-08-[web.1]: [31-Aug-2017 22:22:06 UTC] PHP Fatal error: Uncaught Error: 
Call to undefined function SendGrid\mb_convert_encoding() in /app/vendor/sendgrid/sendgrid/lib/helpers/mail/Mail.php:745
[web.1]: Stack trace: 
[web.1]: #0 /app/index.php(36): SendGrid\Content->__construct('text/html', '<table style='b...')
[web.1]: #1 {main} [web.1]: thrown in /app/vendor/sendgrid/sendgrid/lib/helpers/mail/Mail.php on line 745

1 个答案:

答案 0 :(得分:0)

我终于解决了这个问题,我所要做的只是在@Neodan说的作曲家中启用mbstring。

相关问题